Pl Vue

Store

创建一个 store

实现通用 store,源码

store 基于 watchreactivenextTick 实现,当然在 vue2.7/3 的版本中也同样适用。

原理很简单,一个全局的响应式数据,通过 watch 监听它的变化来更新数据。若通过数据直接修改,再次将数据归位到原先的值,只能通过 store 提供的 actions 来更新数据。 另外 store 不提供 getter 方法,作者认为在实际开发中并不实用,完全可以用计算属性代替。

// store/count.ts
import { defineStore } from "pl-vue/lib/store";

const state = {
  count: 0,
}

const actions = {
  addCount() {
    state.count++;
  },
}

export default defineStore({ state, actions });

使用 store

// app.tsx
import useStore from "./store/count";

function App() {
  const store = useStore();

  return <div>
    <h1>{() => store.count}</h1>
    <button onclick={store.addCount}></button>
  </div>
}