pinia
1.安装
npm install pinia
2. 引入
main.js
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const pinia = createPinia()
const app = createApp(App)
app.use(pinia)
app.mount('#app')
3. 创建文件
在 src 文件中,创建 store 文件,里面按模块创建 ts 文件(也可以是 js)。----user.js
命名方式建议统一规范 use + id + store,示例 useUserStore ,id 为 user。
在store/user.js里
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
state: () => ({
userInfo: {}
}),
actions: {
SetUserInfo(data: any) {
this.userInfo = data
}
}
})
4. 使用
先引入模块,再将引入的模块对象赋值给变量 store (命名随意),如果不需要修改数据,用 const 声明变量,需要修改数据则使用 let 声明。
注意:引入的模块对象名要与模块中 export const 声明的一致。
import { useUserStore } from '@/store/user'
const store: any = useUserStore()
console.log(store.userInfo)
5. 修改数据
修改数据多种方法,可以直接修改,也可以使用 actions 修改。
方法1:直接修改
import { useUserStore } from '@/store/user'
const store = useUserStore()
store.userInfo = obj // obj 指新值
方法2:借助 actions 修改
import { useUserStore } from '@/store/user'
const store = useUserStore()
store.SetUserInfo(obj) // obj 指新值
方法3:多属性修改
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
state: () => ({
name: null,
age: null,
sex: null,
}),
})
上面的方法都是用来修改单个属性的,如果你需要一次修改多个属性,虽然你可以重复操作上面的方法,但是 pinia 提供了新的方法,我更推荐使用官方推荐的方法。
import { useUserStore } from '@/store/user'
const store = useUserStore()
// 你可以这样去修改(不建议)
store.name = '张三'
store.age = 24
store.sex = '男'
// 推荐使用下面这种方式 √
store.$patch({
name: '张三',
age: 24,
sex: '男',
})