我想在组件的store.state中传递值,但出现错误:
[Vue warn]: Error in render: "TypeError: Cannot read property 'state' of undefined"
所以我直接在组件中调用了该值,但它不起作用。
const store = new Vuex.Store({
state: {
filter: {
selected: false,
value: 'test'
}
},
});
new Vue({
el: '#app',
template: `<div id="app"><div :selected="this.$store.state.filter.selected">Option</div></div>`
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/vuex@3.0.1/dist/vuex.js"></script>
<div id="app"></div>
Vue
const store = new Vuex.Store({
state: {
filter: {
value: 'test',
selected: true
}
},
mutations: {},
actions: {},
getters: {}
});
HTML
<option :selected="store.state.filter.selected">{{store.state.filter.value}}</option>
我可以以这种方式使用它,还是需要以不同的方式思考以及如何思考?谢谢。
我当前的解决方案是将值存储在计算变量中,但是是否可以将Vuex存储值直接传递到组件中?
computed: {
filter () {
return storeLogs.state.filter;
}
}
<option :selected="filter.selected">{{filter.value}}</option>
答案 0 :(得分:0)
两件事:
store
对象传递给Vue构造函数const store = new Vuex.Store({
state: {
filter: {
selected: false,
value: 'test'
}
},
});
new Vue({
store, // add store object to Vue
el: '#app',
template: `<div id="app"><div selected="$store.state.filter.selected">Option</div></div>`
});
您还可以在.vue文件中像这样使用mapState
:
<!-- MyComponent.vue -->
<template>
<option :selected="filter.selected">{{filter.value}}</option>
</template>
<script>
import { mapState } from 'vuex';
export default {
name : 'MyComponent',
computed() {
...mapState(['filter'])
}
}
</script>