持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第9天,点击查看活动详情
简介
vue除了vuex状态库之外,还有一个最近非常流行的pinia状态库
上手试了一下,使用简单,容易上手,对小白非常友好
引入
安装引入
npm install pinia
创建 src/pinia/index.js
import { createPinia } from "pinia";
const store = createPinia()
export default store
入口引入 main.js
import store from './pinia'
app.use(store)
概念
- defineStore: StoreDefinition接口类型的方法,定义了一个Store,接收属性行为定义
- State: 定义属性,支持返回和双向绑定
- Getters: 计算操作,依赖State,当State属性有改变时生效
- Actions: 行为操作,pinia提供的操作State的方法
例子
创建 src/pinia/test.js 例子
id: store唯一名称,在多个store相互引用,调用时使用
import { defineStore } from "pinia";
export const useTestStore = defineStore({
id: 'test',
//定义2个数据
state: () => {
return {
name: "li",
age: 8
}
},
//返回age数据
getters: {
getInfo: (state) =>{
console.log(state.age)
return state.age
}
},
//更新age数据
actions: {
updateInfo() {
this.age++
}
}
})
页面
创建 components/test.vue 组件
该组件中 写了3个双向绑定获取pinia定义的State数据,2个按钮来计算和操作State的数据
访组件使用的vue响应式语法,如果使用setup语法,请往下看setup语法部分
//响应式语法
<template>
<div>
<p>this is pinia</p>
<div>
name: {{ testStore.name }}
<p></p>
age: {{ testStore.age }}
</div>
<div>
<el-button type="primary" @click="addAge">增加年龄</el-button>
</div>
<div>
<el-button type="info" @click="getAge">查看信息</el-button>
</div>
<div>
{{ age }}
</div>
</div>
</template>
<script>
import { useTestStore } from '@/pinia/test'
export default {
name: 'test',
data() {
return {
age: null,
testStore: useTestStore()
}
},
methods: {
addAge(){
this.testStore.updateInfo()
},
getAge() {
this.age = this.testStore.getInfo
}
}
}
</script>
setup语法看上去确实易读,代码量也少了,this也没了
//setup语法,只需改变script部分
<script setup>
import { useTestStore } from '@/pinia/test'
import { ref } from 'vue'
const testStore = useTestStore()
//变量
const age = ref(null)
//无参函数
const addAge = () => {
testStore.updateInfo()
}
//无参函数
const getAge = () => {
age.value = testStore.getInfo
}
</script>
效果图
结语: pinia用起来超容易上手,入门门槛比较低,在vue3中感觉pinia会比vuex更受欢迎了