Vuex
store实例的创建
const store = new Vuex.Store({
state: {},
mutations: {},
actions: {},
getters: {},
modules: {}
})
const app = new Vue({
store
})
// 在各个组件中我们都可以获取到this.$store
/*
有了this.$store,我们就可以
获取state this.$store.state.xxx
获取state this.$store.getters.xxx
提交mutation this.$store.commit('mutation', 要传递的数据)
分发action this.$store.dispatch('action', 要传递的数据)
*/
vuex由 state、mutations、actions、getters、modules 组成
state
state用于存储网页中对应组件的所有的数据
const store = new Vuex.Store({
state: {
msg: '数据'
}
})
如果想要组件中使用,可以使用以下方法
const com = {
computed: {
msg () {
return this.$store.state.msg
}
}
}
getter
getter的作用,用于从state中动态获取相关数据
const store = new Vuex.Store({
state: {
arr: [1,2,3,4]
},
getters: {
arrLength (state, getters) {
return state.arr.length
},
demo (state, getters) {
return (num) => {
return num
}
}
}
})
如果要使用getter
const com = {
computed: {
arrLength () {
return this.$store.getters.arrLength
},
demo () {
return this.$store.getters.demo
}
}
}
/*
使用arrLength时可以直接
{{arrLength}}
{{demo(23)}}
*/
mutation
mutation是唯一能够修改state的操作。我们如果想要改变state,就直接的去创建一个mutation,然后提交(commit)这个mutation即可。一般我们会在action进行commit操作
const store = new Vuex.Store({
state: {
msg: '默认数据'
},
mutations: {
changeMsg (state, payload) {
state.msg = payload.msg
}
}
})
如果要使用对应的mutation
this.$store.commit('changeMsg', {
msg: '新的内容'
})
action
我们可以在action中请求接口,获取对原始数据进行处理。action就是为了得到数据的,得到数据后,需要将数据处理并提交给mutation,让mutation对数据进行处理
const store = new Vuex.Store({
state: {
msg: '数据'
},
mutations: {
setMsg (state, msg) {
state.msg = msg
}
},
actions: {
// context就是个store
getMsg ({commit}, payload) {
axios.get(url, data).then(res => {
// 假设res.data就是我们的新的msg
commit('setMsg', res.data)
})
}
}
})
如果我们要使用action
this.$store.dispatch('getMsg', 参数)
因为action是异步的,所以我们可以通过下面的方式来获取到异步的结果
// 将action中异步请求renturn即可
{
actions: {
getMsg ({commit}, payload) {
return axios.get(url, data).then(res => {
// 假设res.data就是我们的新的msg
commit('setMsg', res.data)
})
}
}
}
this.loading = true
this.$store.dispatch('getMsg', 参数).then(() => {
// action中的请求结束后执行的函数
this.loading = false
})
vuex的数据经历了一个循环
组件中想要获取数据 --dispatch–> action --commit–> mutation --mutate–> state --render–> 组件上