Vuex:记录全局变量,记录其中的变量在所有组件中皆可访问,并且是响应式的。
1.修改状态:通过组件修改state的流程如上图,先通过Dispatch提交到服务器(如果没有就跳过),接着通过commit到Mutations(到此改变的记录会被Devtools记录),由Mutations来改变state中属性的状态。
当不传递参数
//store/index中
state: {
//定义全局的状态属性
num: 0
}
mutations: {
sub(state) {
state.devnum--
}
}
//在组件中
<button @click='sub1'></button>
methods: {
sub1() {
this.$store.commit('sub')
}
}
当要传递参数时,与不传递参数的情况相似:
//store的index中
state: {
devnum: 0
}
mutations: {
sub2(state,count) {
state.devnum -= count
}
}
//在子组件中
<button @click='sub1'></button>
methods: {
sub1() {
let count = 2
this.$store.commit('sub2',count)
}
}
注:当要传递多个参数时,显然是用一个对象包裹传递最好,同时也只能通过对象包裹多个参数传递参数
2.vuex中的计算属性
//在router的index中
state: {
num: 0
}
getters: {
//第一个参数必是state
vxnum(state) {
return state.num * state.num
}
}
可以在计算属性中使用其他计算属性:
state: {
carList: [
{name:'你猜',price:10},
{name:'你猜',price:20},
{name:'你猜',price:30},
{name:'你猜',price:40},
{name:'你猜',price:50},
{name:'你猜',price:60}
]
}
getters: {
goodsgt(state) {
//返回单价大于30的商品
return state.carList.filter(n => n.price > 30)
},
//将getters传给totalprice
totalprice(state,getters) {
return getters.goodsgt(state).reduce((s,n) => s + n.price,0)
}
}
如何在计算属性中传参:
getters: {
goodsself(state,getters) {
//return function(price) {
//return state.carList.filter(n => n.price > price)
//}
//上述代码可以简化为
return price => state.carList.filter(n => n.price > price)
}
}
3.异步处理操作Actions
一般在此和服务器进行交互
在其中要想更改全局状态同样需要使用commit方法:
//在router的index文件中
state: {
num: 0
},
mutations: {
cnum(state) {
state.num = 99
}
},
actions: {
//demo(context) {
//setTimeout(() => {
//context.commit('cnum')
//},3000)
//}
//可以对context进行结构
demo({state,commit,getters}) {
setTimeout(() => {
context.commit('cnum')
},3000)
}
}
//在组件中
<button @click='cnum'></button>
methods: {
cnum() {
//与使用mutations类似,使用actions需要调用dispatch
this.$store.dispatch('demo')
}
}
如何传递参数:
//与mutations传递参数类似
//在router的index中
actions: {
demo({state,commit,getters},payload) {
console.log(payload) //payload是传递的一个对象参数
}
}
4.Moduls
可以划分用户,文章等多个模块,每个模块中有自己的state、getters、actions等,以便于管理同类型数据的状态。
如何获取和改变Moduls中的数据:
//在组件中
<div>{{`$`store.state.user.name}}</div> //一定是`$`store.state.user
//在router的index中
let user = {
state: {
name: '张辉'
},
mutations: {
//在mutations中改变属性状态,方法名不可重复,不可和外部mutations中的方法名重复
changeName(state,payload) {
state.name = payload
}
}
}
export default createStore({
modules: {
user
}
})
//组件中
<button @click='changeName'></button>
methods: {
changeName() {
let name = '王喜'
$store.commit('changeName',name)
}
}
在module中获取外层的属性:
//router的index中
const user = {
state:() => {
name: '张辉'
},
getters: {
fullname(state,getters,rootState,rootGetters) {
//rootState即为外层state
//rootGetters即为外层getters
}
}
}