pinia
pinia的优点
1.vue3、vue2、都支持
2.抛弃了Mutations的操作,只有state、getters和actions
3.不需要嵌套模块,符合vue3的Composition api
4.完整的typescript支持
5.代码更加简洁
挂载pinia
在main.ts
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import {createPinia} from 'pinia'
import './assets/main.css'
const app = createApp(App)
const pinia=createPinia()
app.use(router)
app.use(pinia)
app.mount('#app')
新建store的仓库
//定义状态容器和数据 //修改容器中的store //仓库中的action的使用 import { defineStore } from 'pinia' export const mainStore = defineStore('main', { state: () => { return { helloworld:'hello world!' } }, getters: {}, actions: {}, })
在页面中引入store
import {mainStore}from '../store/index.ts'
const store=mainStore()
<h1>{{store.helloworld}}</h1>
在处理状态的action时,有多种方式
第一种:在引入store页面中,直接给button加上点击事件,直接给store.xxx进行修改
<h1 @click="changtxt">{{store.helloworld}}</h1>
const changtxt=()=>{
store.helloworld='welcome to pinia'
}
第二种,在引入store页面中,给button加上点击事件,通过在store.$patch中进行修改
<h1 @click="changtxt">{{store.helloworld}}</h1>
<h2 >{{store.name}}{{store.age}}</h2>
const changtxt=()=>{
console.log('111');
store.$patch({
helloworld:store.helloworld='welcome to pinia',
name:'刘备',
age:44
})
}
第三种
const changtxt=()=>{ store.$patch((state)=>{ state.helloworld='welcome to pinia'; state.name='关羽'; state.age=44 }) }
第四种,使用store中的actions中定义的行为
import { defineStore } from 'pinia'
export const mainStore = defineStore('main', {
state: () => {
return {
helloworld: 'hello world!',
age: 10,
name:'jack'
}
},
getters: {},
actions: {
changeState() {
this.age = 100,
this.name = '赵云',
this.helloworld='三国'
}
},
})
const changtxt=()=>{
store.changeState();
}
getters的使用
用例说明:使用store的getters获取数据,在更改数据之后,还会自动调用getters中的函数
import { defineStore } from 'pinia'
export const mainStore = defineStore('main', {
state: () => {
return {
helloworld: 'hello world!',
age: 10,
name: 'jack',
phone:'12345678912'
}
},
getters: {
phoneHidden(state) {
return state.phone.toString().replace(/^(\d{3})\d{4}(\d{4})$/,'$1****$2')
}
},
actions: {
changeState() {
this.age = 100,
this.name = '赵云',
this.helloworld='三国'
}
},
})
<h1>{{store.phoneHidden}}</h1>
<button @click="changePhone">改变电话号码</button>
const changePhone=()=>{
store.phone='22222222222'
}
获取其他store的数据
1.通过actions获取
actions: { changeState() { this.age = 100, this.name = '赵云', this.helloworld='三国' }, getOtherList() { console.log(otherStore().list); } },
2.通过getters获取
getters: { phoneHidden(state) { return state.phone.toString().replace(/^(\d{3})\d{4}(\d{4})$/,'$1****$2') }, //获取其他store的getter otherGetter(state) { return otherStore().name } },

浙公网安备 33010602011771号