1.vuex的基本语法
store/index.js
import { createStore } from 'vuex'
// vuex 数据管理框架
// vuex 创建了一个全局唯一的仓库,用来存放全局的数据
export default createStore({
state: {
name: 'zhangsan'
},
// mutation里面只允许写同步代码,不允许写异步代码 异步的操作放在actionas里面
// commit 和 mutation 做关联
mutations: {
// 第四部,对应的mutation 被执行
change(state, str) {
// setTimeout(() => {
// 第五部,在mutation里面修改数据
// state.name = str
// }, 2000)
state.name = str
}
},
// dispatch 和 actions做关联
actions: {
// 第二部,store感知到你触发了一个叫做change的action,执行change
change(store, str) {
// 第三部,提交一个commit 触发一个 mutation
setTimeout(() => {
this.commit('change', str)
}, 2000)
}
},
modules: {}
})
Home.vue 1.dispatch方法,派发一个 action, 名字叫做change 2.感知到 change 这个action, 执行store中actions下面的change 3.commit 提交一个叫做change的数据改变 4.mutation 感知到提交的change改变,执行change方法改变数据
<template>
<div class="about">
<h1 @click="handleClick">This is an about page</h1>
<h2>{{name}}</h2>
</div>
</template>
methods: {
handleClick() {
// this.$store.commit('change')
this.$store.dispatch('change', 'hello world')
}
}
2.compositionAPI中如何使用vuex
通过
import { toRefs } from 'vue'
import { useStore } from 'vuex'
export default {
name: 'About',
setup() {
const store = useStore()
const { name } = toRefs(store.state)
const handleClick = () => {
store.dispatch('change', 'hello')
}
return { name, handleClick }
}
}