前提:在mpvue安装了vuex
使用:
1)创建store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
address: ''
},
mutations: {
setAddress (state, newAddress) {
state.address = newAddress
}
},
actions: {
setAddress ({ commit }, newAddress) {
commit('setAddress', newAddress)
}
}
})
2)使用:
方法一:
// 导入store
import store from '../../store'
//在方法中调用
cityChoose (name) {
store.commit('setAddress', name)
//或者是
store.dispatch('setAddress', name)
}
方法二:
使用vuex辅助函数
注意小程序以多页形式渲染,故每个页面都需要创建vue实例并引入相应的store模块
在pages中的main.js导入vuex和store
import Vue from 'vue'
import Vuex from 'vuex'
import App from './index'
import store from '../../store'
Vue.use(Vuex)
// 重要,否则会出现辅助函数不能使用问题
Vue.prototype.$store = store
const app = new Vue({
...App,
store
})
app.$mount()
在页面中的使用
import { mapActions } from 'vuex'
methods: {
...mapActions(['setAddress']),
cityChoose (name) {
this.setAddress(name)
}
}
vuex module模块使用
在store/modules新建app.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default {
namespaced: true,
state: {
address: ''
},
mutations: {
setAddress (state, newAddress) {
state.address = newAddress
}
},
actions: {
setAddress ({ commit }, newAddress) {
commit('setAddress', newAddress)
}
}
}
在index.js中使用
import Vue from 'vue'
import Vuex from 'vuex'
import app from './module/app'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
app
}
})
使用
在main.js中
import store from '../../store'
// 重要,否则会出现辅助函数不能使用问题
Vue.prototype.$store = store
在使用页面中
import { mapState, mapActions } from 'vuex'
computed: {
...mapState('app', ['address'])
},
methods: {
...mapActions('app', ['setAddress']),
cityChoose (name) {
this.setAddress(name)
}
}