1.在store文件里件test.js文件
const test = { namespaced: true, //要设置的全局访问的state对象 state: { obj:{ name:'测试', id:1, } }, mutations: { //改变当前obj changeObj(state, code) { state.obj= code }, }, actions: { //code作为形参 改变数据 触发一个mutation changeObjAction(context,code){ context.commit('changeObj',code) }, } } export default test;
2.在stote文件夹里的index.js引入
import Vue from 'vue' import Vuex from 'vuex' import test from './test' Vue.use(Vuex); export default new Vuex.Store({ modules: { test: test, } })
3.修改
<Test :items="list" :on-click="onDropClick" ></Test> export default { name: "Test", components: { Test }, data() { return { list: [ // 这个传到子组件 {name: '测试', id:1}, {name: '测试1', id:2}, ] }, methods: { // 选中城市 onDropClick(item) { this.$store.dispatch('test/changeObjAction', item) } },
4.使用
computed: { testComputed () { return this.$store.state.test.obj },