pinia中action支持同步和异步
pinia中只有state、getter、action,抛弃了Vuex中的Mutation
pinia中每个store都是独立的,互相不影响
安装
npm install pinia -S
引入,编辑main.js
import { createPinia } from "pinia";
const pinia = createPinia();
const app = createApp(App);
app.use(pinia);
创建store
\src\store\test.js
import { defineStore } from 'pinia'
export const usersstore = defineStore('users', {
state: () => {
return { //state的值定义一定要这么写
name: "111小猪课堂",
age: 25,
sex: "男",
};
},
getters: {
getAddAge: (state) => {
return state.age + 100;
},
},
actions: {
saveName(name) {
this.name = name; //修改state的name值
},
},
})
state
<div>{{age}}</div>
<button @click="changebtn">点击</button>
import {usersstore} from "@/store/test";
//调用:
var {name,age,sex} = usersstore()
var age = ref(age)
//修改数据不响应
var changebtn = ()=>{
usersstore().age=usersstore().age+1 //数据修改成功,但不响应
console.log(usersstore())
}
//推荐,修改数据可以响应
import {storeToRefs} from 'pinia'
var {name,age,sex} = storeToRefs(usersstore()) //在外面包裹一层storeToRefs,
var age = ref(age)
usersstore().age=usersstore().age+1 //数据修改成功,同时也能响应
//批量修改数据
var changebtn = ()=>{
usersstore().$patch({ //缺点就是不需要修改的数据也要写出来
name: "111小猪课堂",
age: 29,
sex: "男",
})
usersstore().$patch((state) => { //这样就可以修改只想改的部分了
state.age=state.age+1
state.sex="女"
})
usersstore().$state = { counter: 666, name: '张三' } //替换整个state数据
}
var changebtn = ()=>{
usersstore().$reset(); //重置所有数据
}
getters
export const usersstore = defineStore('users', {
state: () => {
return { //state的值定义一定要这么写
name: "111小猪课堂",
age: 25,
sex: "男",
};
},
getters: {
getAddAge: (state) => { //相当于在state新增了一个getAddAge变量
return state.age + 100;
},
getNameAndAge: (state) => {
return this.name + this.getAddAge; // 调用其它getter
},
},
})
接收外来参数
getters: {
getAddAge: (state) => { //相当于在state新增了一个getAddAge变量
return (num) => state.age + num;
}
},
调用
{{ usersstore().getAddAge(2) }}
actions
actions: {
saveName(name) {
this.name = name; //修改state的name值
},
},
调用
// 调用actions方法
const saveName = () => {
usersstore().saveName("我是小猪");
};
createPinia //初始化创建pinia
defineStore //创建store
storeToRefs //修改store数据实现数据响应
state //理解成data
store.$reset(); //初始化数据
store.$patch //批量修改数据
store.$state //直接替换state数据
getter //理解成computed
它的作用就是返回一个新的结果,既然它和Vue中的计算属性类似,那么它肯定也是会被缓存的,就和computed一样。
actions //理解成methods ,支持调用同步、异步方法
数据持久化
也就是vuex把数据存到localStorage中
npm i pinia-plugin-persistedstate -S
\src\store\index.js
import { createPinia } from "pinia";
const pinia = createPinia();
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
pinia.use(piniaPluginPersistedstate)
export default pinia
\src\store\user.js
.
.
.
state: () => {
return {
token: getToken(),
menus: [],
};
},
getters: {
},
actions: {
},
// persist:true, //将全部数据缓存到localStorage
persist: {
// 自定义字段名
key: 'mychannel',
// 只是将token字段持久化存储
paths: ['token']
}

https://zhuanlan.zhihu.com/p/533233367