簡體   English   中英

如何在Nuxt中的組件和頁面的腳本部分訪問vuex

[英]How to get access to the vuex in script part of components and pages in Nuxt

我在 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'
})

鑒於您確實正確設置了 Vuex,您應該能夠訪問全局 $store 變量上的狀態。

並且您無法在 Vue 范圍之外訪問或“動態”定義或使用這些變量。

所以 - 回答你的問題 - 將您的代碼更改為:

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

此外,您的 store/index.js 不應export const state ,而應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

但是,無論您要實現什么,這都可能被視為訪問組件的“非常規”方式,但我不知道您要實現什么,這將是對實際問題的回應。 . 但是現在您將擁有多組非常相似的組件。

當我嘗試不同的事情時,唯一對我有用的是使用<component :is="" />和計算屬性:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM