store/module/user.js代码
import Vue from 'vue'
import Vuex from 'vuex'
const state = {
liu:'jingna',
wei:['yu','ning']
}
const mutations = {
changeName(state,res){
state.liu = res
}
}
const actions = {
changeNameA(context){
context.commit('changeName','南京')
}
}
export default {
state,mutations,actions
}
store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import user from "./module/user"//导入其他分模块vuex
Vue.use(Vuex)
export default new Vuex.Store({
modules:{
user,//使用模块
},
state: {
count:7777
},
mutations: {
change(state, value){
// eslint-disable-next-line no-console
console.log(value)
// eslint-disable-next-line no-undef
state.count=value
},
},
actions: {
changevalue(context,params){
context.commit("change",params.count)
}
}
})
在VUE组件中使用
1.第一种方法使用vuex中的扩展方法..mapState、...mapActions
详细代码
import { mapActions, mapState } from "vuex";
export default {
name: "about",
data() {
return {};
},
computed: {
...mapState(["count"]),//获取state的值,html渲染直接使用{{count}}
},
methods: {
...mapActions(["changevalue"]),//导入action方法
add() {
this.changevalue({count:20})//使用action方法改变state的值
},
}
}
2.第二种方法使用实例中的this.$store.state、this.$store.commit()
详细代码
export default {
name: "about",
data() {
return {};
},
computed: {
count: {
get() {
return this.$store.state.count;//获取state的值
}
},
methods: {
add() {
this.$store.dispatch("changevalue", { count: 25 });//通过dispatch触发action上的方法改变state的值
},
namec() {
this.$store.commit("changeName", "深圳");//通过commit触发mutations上的方法改变state的值
}
}