状态管理的工具
可以存用户的登录状态 用户名称 头像 商品收藏 购物车物品
使用
index.js
//引入vue
import Vue from 'vue'
//引入vuex
import Vuex from 'vuex'
//通过vue.use安装 vuex
Vue.use(Vuex)
//创建对象 new Vuex 使用里面的Store方法
var vuex = new Vuex.Store({
state: {
counter:1000//获取方式 {{$store.state.counter}}
},
mutations: {
},
actions: {
},
getters: {
},
modules: {
}
})
//导出
export default vuex
main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
//将vuex导出来
import store from './store'
Vue.config.productionTip = false
new Vue({
router,
store,//使用
render: h => h(App)
}).$mount('#app')
state
//设置共享的内容
state: {
},
eg:
state: {//设置共享内容
counter:1000,
},
获取设置的值: $store.state.counter //其他组件中使用方式
mutations
//修改state中的内容
mutations: {
},
eg:
mutations: {//修改共享的内容 在里面定义方法 默认有个state参数包含着共享的内容
increment(state){
state.counter++;
},
decrement(state){
state.counter--
}
},
使用mutations中设置的方法:
methods: {
add() {//通过$store.commit()方法 里面传入在mutations中设置的方法名进行调用
this.$store.commit("increment");
},
sub() {
this.$store.commit("decrement");
}
},
传递参数
直接在mutations对象中添加方法
incer5(state,data){//直接添加参数
state.counter+=data;
}
使用在methods:方法中通过commit方法传入
add5(count){
this.$store.commit('incer5',data);
}
mutations提交风格
第一种:传递的参数mutations接收的传递的数
this.$store.commit('incer5',data);
第二种:第二种传递的参数mutations接收的是一个对象
this.$store.commit({
type:'incer5',//mutations中的方法名
count:data //需要传的参数
})
在mutations给state中的对象添加新属性可以使用
Vue.set(对象名,'新加的属性','属性值'); //可以实现响应式 直接添加在页面中不会显示
在mutations给state中的对象删除属性可以使用
Vue.delete(对象名,‘删除的属性’)
actions
mutations处理数据 actions接收异步数据
actions: {
},
不在mutations中进行异步操作 比如网络请求 Actions类似于Mutation但是是代替mutations进行异步操作的
eg:
actions: {
aUpdataInfo(context){
setTimeout(() => {
// 修改数据还是必须通过mutations中的方法
context.commit("incer5",5)
}, 1000);
}
},
使用:通过dispatch方法 如果传递参数也是在actions中的方法中写参数 在dispatch中直接传;注意参数可以穿方法、传对象
add5(count){
this.$store.dispatch("aUpdataInfo");
}
getters
用于对state中的数据进行处理相当于vue中的computed属性
getters: {
},
eg:
getters: {
coms(state){
return state.counter * state.counter;
}
coms(state,getters){//getters中还可以把getters对象当做参数进行接收可以通过getters.方法获取里面的方法
return state.counter * state.counter;
}
},
获取值:$store.getters.coms
如果想对getter对象中的方法传递参数
getters: {
coms(state){
return function(c){//方法:返回一个带参数的方法 从方法中在进行返回对state操作的值
return state.counter+c;
}
}
},
$store.getters.coms(8)//传参
modules
可以进行模块的划分
把按模块进行区分方便管理
modules: {
}
eg:
modules:{
a:{
state:{}
actions:{}
mutations:{}
getters:{}
},
b:{
state:{}
actions:{}
mutations:{}
getters:{}
},
}
获取:$store.state.a.定义的属性
mutations actions getters用法相同
getters如果想获取到根getters中的内容需要添加第三个参数rootState