vue3 如何封装函数实现vuex的功能
1、首先封装一个ts文件,导出自定义的useMyStore方法,里面包含自定义的state和action
import { reactive } from 'vue'
interface stateInterface {
font: string
}
// 定义state,存储变量
const state = reactive<stateInterface>({
font: '111'
})
function updateFont(val: string) {
state.font = val
}
// 定义action ,用于修改state的变量
const action = {
updateFont
}
const useMyStore = () => {
const store = {
state,
action
}
return store
}
export default useMyStore
2、在组件1中使用state的值
<h1>{{myStore.state.font}}</h1> // 值为111
import useMyStore from '/*文件路径*/'
setup() {
const myStore = reactive(useMyStore()) //使state中的值变为响应式的
return {
myStore
}
}
3、在组件2中修改state的值
<div @click='changeState'>点击修改state的值</div>
import useMyStore from '/*文件路径*/'
setup() {
const myStore = reactive(useMyStore()) //使state中的值变为响应式的
const changeState=()=>{
myStore.action.updateFont('222') //点击触发updateFont方法,此时组件1中h1的值变为222
}
return {
myStore,
changeState
}
}