[英]Vuex state keeps saying its undefined
這里是我的post.js
下src > store > post.js
:
import Vuex from 'vuex'
import Vue from 'vue'
import axios from 'axios'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
testState: 'Hello',
TV: 0,
},
getters: {
},
mutations: {
},
actions: {
}
})
我的index.js
:
import Vue from 'vue'
import Vuex from 'vuex'
import post from './post'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
},
mutations: {
},
actions: {
},
modules: {
post
}
})
最后我嘗試訪問 component.vue 中的狀態:
<template>
<div id="app">
<h3>{{ testState }} {{ TV }}</h3>
</div>
</template>
<script>
import store from './store'
import { mapActions, mapState, mapGetters } from 'vuex'
export default {
name: 'App',
data(){
return {
}
},
computed: {
...mapState(['testState'])
}
}
</script>
但是,它一直在控制台上給我一個錯誤,上面寫着:
Property or method "testState" is not defined on the instance but referenced during render.
當我檢查 Vue 面板(Chrome 的 devtools)並在 Vuex 下檢查時,我可以清楚地看到testState: 'hello'
there 所以狀態存在。
任何提示/建議? 非常感謝!
你可以試試這個。 您可以使用命名空間模塊
// post.js
import axios from 'axios'
export default {
namespaced: true,
state: {
testState: 'Hello',
TV: 0,
},
getters: {
getTestState: state => state.testState
},
mutations: {
setTestState(state, payload) {
state.testState = payload
}
},
actions: {
setTestState({ commit }, payload) {
commit('setTestState', payload)
}
}
}
// index.js
import Vue from 'vue'
import Vuex from 'vuex'
import post from './post'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
},
mutations: {
},
actions: {
},
modules: {
post
}
})
// Component
computed: {
...mapState('post', ['testState', 'TV']),
...mapGetters('post', 'getTestState') // this.getTestState
},
methods: {
...mapActions('post', ['setTestState']) // this.setTestState('hello from action')
}
由於您使用的是模塊,請嘗試:
...mapState({testState:state=>state.post.testState})
你的模塊不應該創建一個商店實例,它應該像:
export default {
namespaced: true,
state: {
testState: 'Hello',
TV: 0,
},
getters: {
},
mutations: {
},
actions: {
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.