Pinia的基本使用,Vuex的替代品
以下操作均在
vue3
基础上进行
安装
npm install pinia
基本使用
1. 在main.js
中引入pinia
import { createPinia } from 'pinia'
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
const pinia = createPinia()
app.use(pinia)
app.mount('#app')
2. 在src
下新建store
目录,并创建index.js
文件
- 定义方式和
vuex
定义方式差不太多,只是用一个defineStore
包起来了,然后state
变成了匿名函数,移除了mutations
;直接在actions
中操作state
的数据,更简洁,更方便。 - 全程可以使用
this
操作state
中定义的数据,注意不要使用箭头函数,会改变this
的指向
import { defineStore } from 'pinia'
export const useMain = defineStore('main', {
state: () => {
return {
count: 0
}
},
getters: {
getDoubleCount () {
return this.count * 2
}
},
actions: {
increment () {
this.count++
},
decrement () {
this.count--
}
}
})
3. 在App.vue
中使用刚刚定义的store
<template>
<div>message: {{ store.message }}</div>
<div>count: {{store.count}}</div>
<div>double count: {{ store.getDoubleCount }}</div>
<div><button @click="store.increment">increment count</button></div>
<div><button @click="decrement">decrement count</button></div>
<div><button @click="resetCount">reset count</button></div>
</template>
<script lang="ts" setup>
import { useMain } from './store/index'
const store = useMain()
const decrement = () => {
store.decrement()
}
const resetCount = () => {
// 可以调用快捷方式,重置state数据
// store.$reset()
store.$patch({
count: 0,
message: 'update message'
})
}
</script>
更新state
中的数据有几种方式
- 调用
actions
中定义的方法,更新state
中的数据 - 官方建议更新数据使用
$patch
方法更新state
数据,中间进行了优化