因此,我正在试验一个使用vue cli创建的新项目,其中我使用了路由器和VueX
因此,在我的HelloWorld.vue文件中,脚本部分包含以下代码:
import { mapState } from 'vuex'
export default {
name: 'hello',
computed: mapState({
msg: 'nombre'
}),有没有一种更直接的方式调用状态中的值?
msg: store.nombre我的vuex存储在根main.js中定义如下:
//vuex
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
nombre: "POS vuex"
}
});
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})发布于 2018-08-02 00:27:40
实际上我是这样找的:
msg: this.$store.state.nombre(我错过了“.state”。部分)
发布于 2018-08-01 23:48:29
一旦你使用mapState As computed,你就可以在该组件中使用this调用这些状态-在模板或脚本部分:
在mapState上使用...操作符,就完成了:
示例:
你的商店:
const store = new Vuex.Store({
state: {
nombre: "POS vuex",
otherState: "abc",
anotherState: "efg"
}
});您的组件:
<template>
<div id="test">
{{ nombre }}
{{ otherState }}
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
name: 'hello',
methods: {
logState() {
console.log(this.anotherState);
}
},
computed: {
...mapState(["nombre", "otherState", "anotherState"]),
}
}
</script>发布于 2019-05-02 20:45:16
除了mapState helper之外
computed: {
...mapState('moduleOne', ['keyOne', 'keyTwo'])
}它允许您通过组件中的this.keyOne和this.keyTwo访问值。
您还可以将您的存储区添加到root vue instance,并通过全局this.$store指令访问组件内部的状态。
this.$store.module.keyOne
this.$store.module.keyTwo此外,如果您需要从组件外部访问存储区,也可以直接从非组件代码中导出和导入存储区。
如果导出您的存储:
import Vue from 'vue'
import Vuex from 'vuex'
import moduleTwo from './modules/moduleOne'
import moduleOne from './modules/moduleTwo'
Vue.use(Vuex)
const store = new Vuex.Store({
strict: true,
modules: {
moduleOne,
moduleTwo
}
})
export default store您可以在需要访问状态、getter、操作和突变的任何地方导入它。
import store from '@/store'
console.log(store.state.moduleOne.keyone)
store.dispatch('moduleOne/actionOne', { keyOne: valOne })
store.getters['moduleOne/getterOne']
store.commit('moduleOne/mutationOne', data)https://stackoverflow.com/questions/51637069
复制相似问题