标签:count counter 05 23 state 2021 commit store mutation
vux
概念:vux是一个专为Vue.js应用程序开发的状态管理模式。也就是管理公共数据的地方。
state
单一状态树,也叫单一数据源,我们可以把需要的数据放里面。
如果里面放置了counter:100,
state:{
counter:100
}
我们可以通过$store.state.counter取出{{$store.state.counter}}
getters
有时候,我们需要从store中获取后写state变异后的状态,比如state*2等一些复杂操作。
getters:{
powercounter(state){
return state.counter*state.counter
}
}
当我们需要取出时
{{$store.getters.powercounter}}
如果需要递归则:
getters:{
powercounter(state){
return state.counter*getters
}
}
//返回函数
mutation
通常情况,Vue要求我们vue的store的更新唯一方式就是:提交mutation
mutation主要包括两部分:
- 字符串的事件类型(type)
- 一个回调函数(handle),该回调函数的第一个参数就是state
mutations:{
increment(state){
state.counter++
},
decrement(state){
state.counter--
},
incrementcount(state,count){
return state+=count
}
}
通过mutation更新的时候,
普通提交封装:
this.$store.commit('increment')
addcount(count){
this.$store.commit('increment',count)
}
特殊提交封装:
this.$store.commit({
type:'incrementcount',
count:count
})
假如有很多参数需要传递,这个时候我们通常会以对象的形式传递,也就是payload是一个对象。
changcount(state,payload){
state.count+=payload.count
}
changecount(){
this.$store.commit('changecount',{count:0})
}
使用常量替代 Mutation 事件类型
// mutation-types.js
export const SOME_MUTATION = 'SOME_MUTATION'
// store.js
import Vuex from 'vuex'
import { SOME_MUTATION } from './mutation-types'
const store = new Vuex.Store({
state: { ... },
mutations: {
// 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名
[SOME_MUTATION] (state) {
// mutate state
}
}
})
action
actions:{
//context上下文
aupdateinfo(context){
setTimeout(()=>{
//必须执行mutation内的方法
context.commit('updateInfo')
},1000)
}
}
//调用的时候
this.$store.dispatch('aupdateinfo',{
payload:'我是携带的信息',
success:()=>{
console.log("finished")
}
})
module
如果需要管理的数据比较多,可以在module中分模块
//取值的时候 this.$store.state.a.name
标签:count,counter,05,23,state,2021,commit,store,mutation 来源: https://blog.csdn.net/cyhhjj/article/details/117193952
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。