vuex 概念#
每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,
1、Vuex 的状态存储是响应式的。
2、你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。
State#
let store = new Vuex.Store({
state:{
count:100,
dataList:[],
title:"aaa",
},
})
1、计算属性获取
computed: {
count () {
return this.$store.state.count
}
}
2、mapState 辅助函数
computed: mapState({
count: state => state.count,
countAlias: 'count',
countPlusLocalState (state) {
return state.count + this.localCount
}
})
3、对象展开运算符
mapState 函数返回的是一个对象。我们将它与局部计算属性混合使用
computed:{
...mapState({
...
})
}
Getter#
从 store 中的 state 中派生出一些状态,例如对列表进行过滤并计数
类似于全局函数的一个计算属性;
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
doneTodos: state => (id)=>{
return state.todos.filter(todo => todo.done)
}
}
})
this.$store.getters.doneTodos(1)
2、mapGetters 辅助函数
computed: {
...mapGetters([
'doneTodosCount',
'anotherGetter',
])
}
...mapGetters({
doneCount: 'doneTodosCount'
})
Mutation#
Mutation 必须是同步函数
mutations:{
// 设置数据
setdata(state,payload){
state.dataList = payload
}
},
// 在组件中提交 Mutation
你可以在组件中使用 this.$store.commit('xxx') 提交 mutation,
或者使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用
methods: {
...mapMutations([
'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
// `mapMutations` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
]),
...mapMutations({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
})
}
Action#
Action 提交的是 mutation,而不是直接变更状态。
Action 可以包含任意异步操作。
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
你在组件中使用 this.$store.dispatch('xxx') 分发 action,
或者使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用
this.$store.dispatch('incrementAsync', {
amount: 10
})
this.$store.dispatch({
type: 'incrementAsync',
amount: 10
})
methods: {
...mapActions([
'increment',
'incrementBy'
]),
...mapActions({
add: 'increment'
})
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步