Vue 说白了就是一个租赁仓库,保存了一些数据,这些数据可以被大家公用,哪个组件想要调用就引入即可,
1.State
什么是vuex-----state?
state及类似与组件中的data数据,既然类似为何还要写在vuex中的state里面呢?
组件中的data数据仅仅是局部的适用于该组件中的使用,其他的组件不能获取使用, 而vuex里面的state数据是全局的可以再任何一个组件使用,但是我们也可以在单个组件中修改这个全局的store state数据,
组件中如何使用state?
首先我们需要把 vuex全局引用,main.js,这里是建立单独文件store故需要引入
//main.js文件
import router from './router';
import store from './store';
new Vue({
router,
store
})
state在组件中使用需要在计算属性接收一下(暂且就理解为是接收吧)
<template>{{a}}或者{{A}}</template>
import {mapState} from 'vuex'
export default{
computed:mapState({'a':A,'b':B})
}
或者
computed:mapState(['A','A'])
mapstate 即可以接受对象,也可以接受数组。最终返回的是一个对象。
2.Mutation
mutations 类似于组件里面的methods在mutations里面可以对state的数据进行修改,比如
state:{
num:[1,2,3,4]
},
mutaions:{
numChange(state){
state.num[0]++
}
}
我们不嫩能够直接调用一个mutation handler这个选项更像是时间注册,“当触发一个类型为incroment”的mutation时2,调用此函数,‘要唤醒一个mutation handler’,你需要以相应的type调用store.commit方法:
store.commit('numChange')3.Action
action的作用
actions 类似于mutations 大体归类到事件;mutation像事件注册,需要相应的条件触发,action像是管理触发条件的;例子如下
mutations:{
sortNum(state,array){
// 在这里就可以变更state里面的数据了
state.num=array.sort()
}
},
actions:{
// action 接收一个commit 或者 state
sortNumStatus({commit},arr){
var array;
arr.forEach(item){
if(item){
array.push(item)
}
}
//条件成立就可以commit Mutataion了,actions 类似于条件触发事件
commit(sortNum,array)
}
}
Action事件怎么触发?
action 在组件中被触发,分发action,或者使用mapActions辅助函数将组件的methods映射为
store.dispatch调用
import {mapActions} from 'vuex';
export default{
methods:{
...mapActions([
'sortNumStatus'
]),
// 或者
...mapActions({
add:'sortNumStatus'
}),
}
}
// 不使用辅助函数mapActions
export default{
methods:{
this.$store.dispath('sortNumStatus',arr);
}
}
4.Getter
getter存放公共函数供组件调用,类似于组件中的过滤函数computed或者filters,组件中的computed和filters只能供给单个组件自己调用不能被多个组件公用,
state:{
arr:4
},
getters:{
evenOrOdd:state=>state.arr%2===0?'event':'odd'
}
<template>{{eventOrOdd}}或者{{eventodd}}</template>
import {mapGetter} from 'vuex';
computed:{
...mapGetters([
'eventOrOdd'
])
}
//或者
computed:{
...mapGetters({
eventodd:'eventOrOdd'
})
}
getter不仅可以接收state也可以接收 其他的 getter 作为参数!