在Vue3中,状态管理工具更加偏向于Pinia,虽然Pinia即支持Options API,也支持Composition API。但我个人倾向于Vue2或者Vue3的Options API使用Vuex,而Vue3的setup写法使用Pinia。
安装
yarn add pinia
# 或者使用 npm
npm install pinia
项目引入
// main.js
import { createPinia } from 'pinia'
// 在app实例化之后use
app.use(createPinia())
创建一个store
// useCart.js
import { defineStore } from 'pinia'
// 第一个参数是应用程序中 store 的唯一 id,就是案例中的"main",类似于vuex的module,好处是不用引入合并了
// 创建store推荐使用"use"开头
export const useCart = defineStore('main', {
// option store写法
// 推荐使用 完整类型推断的箭头函数
state: () => {
return {
// 所有这些属性都将自动推断其类型
counter: 0,
name: 'Eduardo',
isAdmin: true,
}
}
})
// 或者 export useCart
使用store
// xxx.vue
<script setup>
import { storeToRefs } from "pinia";
import { useCart } from './useCart.js';
const store = useCart();
// 这样就可以直接使用store.counter,store.name...
---------分割线--------
// 注意:千万不要用解构,否则数据会失去响应式,就像下面这种
const { counter, name, isAdmin } = store;
// 如果你真的想解构,可以使用pinia提供的storeToRefs api,首先store上方引入
const { counter, name, isAdmin } = storeToRefs(store);
</script>
修改store的值
// xxx.vue
<script setup>
import { useCart } from './useCart.js';
const store = useCart();
// 第一种:直接通过store.的方式修改
store.counter = 2;
store.name = "Bob";
// 第二种:通过补丁的方式,将来会和state里面对应值进行合并覆盖
store.$patch({
counter:1
})
// 第三种:恢复初始值(严格意义不算第三种)
store.$reset()
</script>
未完待续...