const app = createApp(App);
import { createPinia } from “pinia”;
const store = createPinia();
app.use(store).mount(“#app”)
* 在store文件夹下新建test.js
import {definePinia} from “pinia”
export default testStore = definePinia(‘testId’,{
state:()=>{
tname:“test”,
tnum:0,
},
getters:{
changeTnum(){
console.log(“getters”)
this.tnum++;
}
},
actions:{
addNum(val){
this.tnum += val
}
},
//持久化存储配置
presist:{
enable:true,//
strategies:[
{
key:“testId”,
storage:localStorage,
paths:[‘tnum’]
}
]
}
})
**`在用actions的时候,不能使用箭头函数,因为箭头函数绑定是外部的this。actions里的this指向当前store`**
* 在store文件夹下新建index.js,便于管理
import {createPinia} from “pinia”
const store = createPinia();
export default store
* 新建`A.vue`组件,引入store模块和`storeToRefs`方法
`storeToRefs`:解构`store`中的数据,使之成为响应式数据
### 三、直接修改数据的两种方式
直接修改数据与使用`$path`修改数据相比,官方已经明确表示`$patch`的方式是经过优化的,会加快修改速度,对程序的性能有很大的好处。所以如果你是多条数据同时更新状态数据,推荐使用`$patch`方式更新。
虽然可以直接修改,但是出于代码结构来说, 全局的状态管理还是不要直接在各个组件处随意修改状态,应放于`actions`中统一方法修改(piain没有mutation)。
//直接修改数据
tchangeName(){
tname.value = “测试数据”;
tnum.value++;
}
//当然也可以使用$path
批量修改
tchangeName(){
testStore.$path(state=>{
state.tname = “测试数据”;
state.value = 7;
})
}
### 四、使用actions修改数据
直接调用`actions`中的方法,可传参数
const actionsBtn = (){
testStore.addNum(5)
}
### 五、重置state中数据
`store`中有`$reset`方法,可以直接对`store`中数据重置
const treset = (){
testStore.$reset()
}
### 六、Pinia持久化存储
* 实现持久化存储,需要配合以下插件使用
yarn add pinia-plugin-persist
* 配置`store`文件夹下的`index.js`文件,引入`pinia-plugin-presist`插件
import {createPinia} from “pinia”
import piniaPluginPresist from “pinia-plugin-presist”
const store = createPinia();
store.use(piniaPluginPresist)
export default store
* 配置stroe文件夹下的test.js文件,使用`presist`属性进行配置
import {definePinia} from “pinia”
export default testStore = definePinia(‘testId’,{
state:()=>{
tname:“test”,
tnum:0,
},
getters:{
changeTnum(){
console.log(“getters”)
this.tnum++;
}
},
actions:{
addNum(val){
this.tnum += val
}
},
//持久化存储配置
presist:{
enable:true,//
strategies:[
{
key:“testId”,
storage:localStorage,
paths:[‘tnum’]
}
]
}
})
* `enable:true`,开启持久化存储,默认为使用`sessionStorage`存储
- `strategies`,进行更多配置
- `key`,不设置key时,storage的key为`definePinia`的第一个属性,设置key值,则自定义storage的属性名
* `storage:localStorage`,设置缓存模式为本地存储
* `paths`,不设置时对`state`中的所用数据进行持久化存执,设置时只针对设置的属性进行持久化存储
### 七、Pinia模块化实现
模块化实现即在store对要使用的模块新建一个js文件,比如`user.js`文件。然后配置内容跟其他模块一样,根据自己需求进行设置,然后在对应页面引入。

### 八、Pinia中store之间互相调用
比如:`test.js`获取`user.js`中`state`的`name`属性值,在`test.js`引入`user.js`
import { defineStore } from ‘pinia’
import { userStore } from “./user.js”
最后
四轮技术面+一轮hr面结束,学习到了不少,面试也是一个学习检测自己的过程,面试前大概复习了 一周的时间,把以前的代码看了一下,字节跳动比较注重算法,面试前刷了下leetcode和剑指offer, 也刷了些在牛客网上的面经。大概就说这些了,写代码去了~
祝大家都能收获大厂offer~
篇幅有限,仅展示部分内容