vuex实现数据共享
1.store.js结构
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { city: '汉中' }, mutations: { }, actions: { } })
2.main.js引入
import store from './store' new Vue({ router, store, render: h => h(App) }).$mount('#app')
3.组件使用State的数据
{{ this.$store.state.city }}
4.用dispatch调用Actions,Actions用commit调用Mutations修改数据
具体组件.vue
methods: { handleClick (city) { this.$store.dispatch('changeCity', city) } }
store.js import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { city: '汉中' }, mutations: { changeCity (state, city) { state.city = city } }, actions: { changeCity (ctx, city) { // ctx为上下文,city是传来的参数 ctx.commit('changeCity', city) } } })
5.数据简单,跳过Actions,直接到Mutations
具体组件.vue methods: { handleClick (city) { this.$store.commit('changeCity', city) } }
store.js import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { city: '汉中' }, mutations: { changeCity (state, city) { state.city = city } } })