【问题标题】:How to get access to the vuex in script part of components and pages in Nuxt如何在 Nuxt 中组件和页面的脚本部分访问 vuex
【发布时间】:2020-10-31 09:36:27
【问题描述】:

我在 Nuxtjs 2.13 上。我正在尝试根据我的 store.state.dir 动态加载我的组件。 像这样:


<script>
import store from 'Vuex';
let siteDirection = store.state.dir
const mm= ()=>import('~/components/'+ siteDirection +'/home/mm.vue')

export default {
  components:{
    'mm': mm
  
}
</script>

但我无法访问我的商店。我该怎么办?

我的store/index.js 文件:

export const state = () => ({
  dir: 'rtl'
})

【问题讨论】:

    标签: vue.js vuejs2 nuxt.js vuex


    【解决方案1】:

    如果你正确设置了 Vuex,你应该能够访问全局 $store 变量的状态..

    而且你不能在 Vue 范围之外访问或“动态”定义或使用这些变量..

    所以 - 回答您的问题 - 将您的代码更改为:

    <script>
    export default { 
      components:{
        'mm': () => import('~/components/'+ this.$store.state.dir + '/home/mm.vue')
    }
    </script>
    

    另外你的 store/index.js 不应该是 export const state 而是一些东西:

    import Vue from 'vue'
    import Vuex from 'vuex'    
    Vue.use(Vuex)
    
    const state = {
    dir: 'rtl'
    }
    
    const store = new Vuex.store({
    state,
    // getters,mutations,actions,modules if you want
    })
    
    export default store
    

    但是,无论您要实现什么,这可能会被视为访问组件的“非传统”方式,但我不知道您要实现什么,这将是对实际问题.. 但是现在您将拥有多组非常相似的组件。

    【讨论】:

    • 在开发双向应用程序时,我在顶层为我的每个组件创建了两个组件。一个在rtl 目录中,一个在ltr 目录中。并根据存储在 vuex 中的我的应用程序 dir 导入和安装它们。很奇怪吗??
    • 我做过this.$store.state.dir,但它给了我Cannot read property '$store' of undefined。我的 vuex 设置按照 nuxt 的指示,在 store 目录中添加了 index.js 并导出了 stategettersmutationsactions 。实际上我的store 工作正常,并且在组件的created() 部分中使用了相同的this.$store.state.dir,一切都很好
    • 我对 nuxt 不是很熟悉,但是我再次检查了问题并编辑了我的回复,您可能想检查您的 store.js 以及上面的内容,也许这就是问题所在?根据您的另一个问题,rtl 和 ltr 之间的相同组件有什么区别?
    【解决方案2】:

    当我尝试不同的事情时,唯一对我有用的是使用 &lt;component :is="" /&gt; 和计算属性:

    <template>
      <component :is="mycomp" />
    </template>
    
    export default {
      computed:{
        mycomp(){
          return ()=>import('@/components/'+ this.$store.state.dir +'/mycomp.vue')
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-19
      • 2021-07-01
      • 2020-08-18
      • 2020-12-07
      • 2021-04-21
      • 2023-02-09
      • 1970-01-01
      • 2019-04-14
      • 1970-01-01
      相关资源
      最近更新 更多