yarn add pinia
# 或者使用 npm
npm install pinia
// main.js中引入
import { createApp } from 'vue';
import App from './App.vue';
const app = createApp(App);
// vue使用pinia
import { createPinia } from "pinia"
app.use(createPinia());
在 src 目录下新建 store 目录,store 目录下新建 demo.ts
import { defineStore } from 'pinia';
export const demoStore = defineStore('demo', {
state: () => {
return {
// 所有这些属性都将自动推断其类型
counter: 0 as Number,
mobile:"13111111111" as String
}
},
getters:{},
actions:{}
})
在页面组件中渲染 state
pinia测试{{counter}}
// 修改上面代码
pinia测试{{counter}}
// 接上述代码片段4.actions修改state
// store/demo.ts
import { defineStore } from 'pinia';
export const demoStore = defineStore('demo', {
state: () => {
return {
// 所有这些属性都将自动推断其类型
counter: 0 as Number,
mobile:"13111111111" as String
}
},
getters:{},
actions:{
// 4.改变state值
add(n:number){
this.counter += n;
},
reduce(n:number){
this.counter -= n;
}
}
})
// store/demo.ts
import { defineStore } from 'pinia';
export const demoStore = defineStore('demo', {
state: () => {
return {
// 所有这些属性都将自动推断其类型
counter: 0 as Number,
mobile:"13111111111" as String
}
},
getters:{
mobileHidden:(state):String => {
return state.mobile.replace(/(\d{3})\d{4}(\d{4})/g,`$1****$2`);
}
},
actions:{
// 4.改变state值
add(n:number){
this.counter += n;
},
reduce(n:number){
this.counter -= n;
}
}
})
// 页面组件中使用同state
pinia测试{{counter}}-{{mobileHidden}}
在 store 目录下新建 test.ts 作为第二个 store
// store/test.ts
import { defineStore } from 'pinia';
export const testStore = defineStore('test', {
state: () => {
return {
list:[1,2,3] as Array
}
},
getters:{},
actions:{}
})
// store/demo.ts
import { defineStore } from 'pinia';
// 引入testStore
import { testStore } from './test';
import { toRaw } from "vue";
export const demoStore = defineStore('demo', {
state: () => {
return {}
},
getters:{},
actions:{
// store互调
getList(){
// 需要先将testStore调用实例化,然后读取里面state
console.log(toRaw(testStore().list))
}
}
})
pinia测试{{counter}}-{{mobileHidden}}