①安装vuex插件
npm install Vuex -S
②在store文件夹下的index.js文件中使用Vuex插件,类似路由
Vue.use(Vuex)
③创建store对象
this.$store.state
属性的方式来访问状态this.$store.commit(‘mutation中的方法‘)
来修改状态const store = new Vuex.Store({
state: {
//counter:共享变量
counter: 1000
},
mutations: {
increment(state) {
state.counter++
},
changeNum(state, count) {
state.counter += count
}
},
actions: {},
getters: {},
modules: {}
})
[注意事项]:我们通过提交mutations的方式,而非直接改变$store.state.counter
,这是因为Vuex可以更明确的追踪状态的变化,所以不要直接改变$store.state.counter
的值
④导出store对象
export default store
⑤将这个store对象挂载到vue实例中
new Vue({
el: ‘#app‘,
store,
render: h => h(App)
})
getters: {
powerCounter(state) {
return state.counter * state.counter
}
cubCounter(state, getters) {
return getters.powerCounter * state.counter
}
moreAgeStu(state) {
return function(age) {
return state.students.filter(s => s.age > age)
}
}
this.$store.getters.moreAgeStu
this.$store.commit(‘mutation中的方法‘)
mutations: {
//increment叫做事件类型,后面部分叫做回调函数
increment(state) {
state.counter++
}
}
@click="changeCounter
changeCounter() {
this.$store.commit(‘changeNum‘, 5)
}
mutations常量类型
//mutations.types.js
export const INCREMENT = ‘increment‘
import {
INCREMENT
} from ‘./store/mutations.types.js‘
addition() {
this.$store.commit(INCREMENT)
}
import * as types from ‘./mutations.types.js‘
[types.INCREMENT](state) {
state.counter++
}
响应式为对象添加或删除属性的方式
// 添加属性
Vue.set(state.info, ‘address‘, ‘洛杉矶‘)
// 删除属性
Vue.delete(state.info, ‘age‘)
updateInfo() {
this.$store.dispatch(‘aUpdateInfo‘, ‘我是携带的信息‘).then(res => console.log(res))
}
actions: {
//context在这里相当于store,payload是携带的信息
aUpdateInfo(context, payload) {
return new Promise((resolve, reject) => {
setTimeout(() => {
context.commit(‘updateInfo‘)
console.log(payload)
resolve(‘111‘)
}, 1000)
})
}
}
mutations:{
updateInfo(state) {
state.counter = 20
}
}
const moduleA = {
state: {
name: ‘小明‘
},
mutations: {},
actions(),
getters: {}
}
const store = new Vuex.Store({
modules: {
a: moduleA
}
})
<h2>{{$store.state.a.name}}</h2>
getters: {
fullName(state, getters, rootState) {
return state.name + rootState.counter
}
}
原文:https://www.cnblogs.com/jincanyu/p/14353588.html