简单使用(存和取)
-
创建:
在js文件里创建仓库:
import Vue from 'vue'
import Vuex from 'vuex'
//挂载Vuex
Vue.use(Vuex)
//创建VueX对象
const store = new Vuex.Store({
state:{
//存放的键值对就是所要管理的状态
name:'helloVueX'
}
})
export default store
-
使用:
使用$store.state.value
获取相应值
在组件方法中使用:
methods:{
add(){
console.log(this.$store.state.name)
}
},
在计算属性中使用:
computed: {
count () {
return this.$store.state.name
}
}
-
高级使用:
使用在计算属性中使用...mapState
:
computed: {
...mapState({
name: state => state.store.name,
sex: state => state.store.sex
// 可以直接用this访问
})
}
Mutations
mutations
是操作数据的方法的集合,比如对该数据的修改、增加、删除等等
-
创建
const store = new Vuex.store({
state:{
name:'helloVueX'
},
mutations:{
//state是当前VueX对象中的state
//payload是参数
edit(state,payload){
Vue.set(state,"age",payload.age) // 修改(不存在则新增)
Vue.delete(state,'age') //删除
}
}
})
-
使用:
this.$store.commit('edit',{age:15,sex:'男'})
或
this.$store.commit({
type:'edit',
payload:{
age:15,
sex:'男'
}
})
-
注意:在修改和删除中要使用Vue提供的方法,否则Vue不能对数据进行实时响应
-
高级使用
可以解构到methods中,方便使用:
methods: {
...mapMutations({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
})
}
Getters
可以对state中的成员加工后传递给外界
-
创建
getters:{
//state 当前VueX对象中的状态对象
//getters 当前getters对象,用于将getters下的其他getter拿来用
nameInfo(state){
return "姓名:"+state.name
},
fullInfo(state,getters){
return getters.nameInfo+'年龄:'+state.age //获取上面那个getter
}
}
-
使用:
this.$store.getters.fullInfo
-
高级使用
计算属性使用...mapGetters
computed: {
...mapGetters({
// 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
doneCount: 'doneTodosCount'
})
}
Actions
mutation不能异步,所以提供了Actions来专门进行异步提交mutation
方法。(action可以在异步操作出结果后再提交给mutation)
-
创建
//context 上下文(相当于箭头函数中的this)对象
//payload 参数
actions:{
aEdit(context,payload){
return new Promise((resolve,reject)=>{
//promise里面是异步提交
setTimeout(()=>{
context.commit('edit',payload)
resolve()
},2000)
})
}
}
-
使用
this.$store.dispatch('aEdit',{age:15})
-
高级使用
同样可以解构到methods,分别使用
methods: {
...mapActions({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
})
}
看懂上面之后,再看这张图就没有压力了: