1.首先了解vuex的用法,实例按vue3创建
2.简易实现vuex
1.1APP.vue
<script setup lang="ts">
import {computed} from "vue";
import {useStore} from '../src/vuextext'
const store = useStore()
const count = computed(() => store.state.count)
const crement = () => {
store.commit('increment')
}
const decrement = () => {
store.dispatch('decrement')
}
</script>
<template>
<div>{{ count }}</div>
<button @click="crement()">+</button>
<button @click="decrement()">+2</button>
</template>
1.2main.ts
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import store from '../src/store'
// 将 store 实例作为插件安装
createApp(App).use(store).mount('#app')
1.3vuex-text
import {inject, reactive,} from "vue";
class Store {
//store对象包含state,mutations,actions
constructor(state, mutations, actions) {
this.state = state;
this.mutations = mutations;
this.actions = actions;
}
//通过install方法拿到传入的state,mutations,actions
//创建store的commit,dispatch方法
//install--一个插件可以是一个拥有 install() 方法的对象
//也可以直接是一个安装函数本身。安装函数会接收到安装它的应用实例和传递给 app.use() 的额外选项作为参数:
install(app) {
const store: Object = new Object()
store.state = reactive(this.state)
store.commit = (mutationName, payload) => {
this.mutations[mutationName](store.state, payload)
}
store.dispatch = (type, payload) => {
this.actions[type]({commit: store.commit, state: store.state}, payload)
}
//通过provide分发store,使每个组件能访问到
app.provide('store', store)
}
}
export function createStore({state,mutations,actions}) {
//通过createStore返回一个实例对象
//包含state,mutations,actions
return new Store(state, mutations, actions)
}
export function useStore() {
//暴露一个useStore方法
//目的是拿到分发的store
const store = inject('store')
return store
}
1.4定义store中的数据
import {createStore} from '../vuextext'
// 创建一个新的 store 实例
const store = createStore({
state:
// return {
// count: 0
// }
{
count:0
}
,
mutations: {
increment(state) {
state.count++
}
},
actions: {
decrement({commit, state}, context) {
console.log(state, commit, context)
setTimeout(() => {
state.count += 2
}, 1000)
}
}
})
export default store