一、简介demo
这里用的vue-cli
引入vuex 1.利用npm包管理工具,进行安装 vuex。在控制命令行中输入下边的命令就可以了。 –save,因为你这个包我们在生产环境中是要使用的。
npm n install vuex --save
2.新建一个vuex文件夹(这个不是必须的),并在文件夹下新建store.js文件,文件中引入我们的vue和vuex。
import Vue from 'vue';
import Vuex from 'vuex';
3.使用我们vuex,引入之后用Vue.use进行引用。
Vue.use(Vuex);
store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex)
//声明一个常量存放 状态对象
const state = {
count:1
}
//声明一个常量,这里方法来控制常量
const mutations = {
add (state){
state.count++;
},
reduce(state){
state.count--;
}
}
//暴露出去
export default new Vuex.Store({
state,
mutations
})
Count.vue
{{msg}}
{{$store.state.count}}
import store from '@/vuex/sotre'
二、state访问状态对象
** 1、通过computed的计算属性直接赋值**
store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex)
//声明一个常量存放 状态对象
const state = {
count:1
}
//声明一个常量,这里方法来控制常量
const mutations = {
add (state){
state.count++;
},
reduce(state){
state.count--;
}
}
//暴露出去
export default new Vuex.Store({
state,
mutations
})
Count.vue
{{msg}}
{{$store.state.count}} - {{count}}
import store from '@/vuex/sotre'
2、通过mapState的数组来赋值
store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex)
//声明一个常量存放 状态对象
const state = {
count:1
}
//声明一个常量,这里方法来控制常量
const mutations = {
add (state){
state.count++;
},
reduce(state){
state.count--;
}
}
//暴露出去
export default new Vuex.Store({
state,
mutations
})
Count.vue
{{msg}}
{{$store.state.count}} - {{count}}
import store from '@/vuex/sotre'
import {mapState} from 'vuex';
三、Mutations修改状态
四、getters计算过滤属性
五、actions异步修改状态
这里面用了简写
1、...扩展运算符
2、import {mapState,mapMutations,mapGetters,mapActions} from 'vuex'
3、达到目的 仓库+本页面的数据控制并存
store.js
import Vue from 'vue'
import Vuex from 'vuex';
Vue.use(Vuex)
// //声明一个常量存放 状态对象
// const state = {
// count:1
// }
// //声明一个常量,这里方法来控制常量
// const mutations = {
// add (state){
// state.count++;
// },
// reduce(state){
// state.count--;
// }
// }
// //暴露出去
// export default new Vuex.Store({
// state,
// mutations
// })
export default new Vuex.Store({
state:{
count:0,
sex:'男'
},
getters:{
count:function(state){
return state.count += 11;
}
},
actions:{
addActions(context){
context.commit('add',10)
setTimeout(()=>{context.commit('reduce')},1000)
console.log('addActions===========')
},
reduceActions({commit}){
commit('reduce')
}
},
mutations:{
add(state,num){
state.count+=num;
// setTimeout(()=>{state.count--},1000)
// console.log('add===========')
},
reduce(state){
state.count--;
}
}
})
Count.vue
{{msg1}}
{{$store.state.count}} -- {{count}}
{{count}} {{sex}}
传递参数
简化调用方法 mapState
异步 mapActions
六、module模块组(项目不大不用)