安装pinia
yarn add pinia
# 或者使用 npm
npm install pinia
配置pinia
在src目录下新建store目录,下面创建对应的js文件,以user.js为例
user.js中
import {defineStore } from 'pinia'
export const useStore = defineStore('users',{
state:()=>{
return{
}
},
getters:{
},
actions:{
}
})
main.js中
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
const app = createApp(App)
import { createPinia } from 'pinia'
const pinia = createPinia()
app.use(pinia).mount('#app')
App中
<script setup>
import { useStore } from "./store/user.js";
const store = useStore()
</script>
state的使用
<template>
<div class="app">
<h2>{{name}}</h2>
<h2>{{age}}</h2>
<h2>{{item}}</h2>
<button @click="changeName">更改姓名</button>
<button @click="reset">重置store</button>
<button @click="patchStore">批量修改数据</button>
<button @click="patchStore2">批量修改但不是全部数据</button>
</div>
</template>
<script setup>
import { useStore } from "./store/user.js";
import {storeToRefs} from 'pinia'//给pinia中的数据添加响应式
const store = useStore()
let {name,age,item} = storeToRefs(store)//storeToRefs为解构赋值,让值具有响应性
const changeName = ()=>{
store.name = '李四'//更改state中的数据storeToRefs
store.age = 50
}
const reset = ()=>{
store.$reset();//重置$reset
}
const patchStore =()=>{
store.$patch({
name:'李四',//批量修改$patch
age:60
})
}
const patchStore2 =()=>{
store.$patch((state)=>{
state.item.push({
name: 'shoes',
quantity: 1
})
})
}
getters的使用
import {defineStore } from 'pinia'
export const useStore = new defineStore('users',{
state:()=>{
return{
item:[{
name:'王五',
age:70
}],
name:'张三',
age:20,
users: [{
id: 1,
name: '张三'
},
{
id: 2,
name: '李四'
},
{
id: 3,
name: '王五'
}
]
}
},
//在getters在一个函数中,调用一个getters里面的另外一个函数 要在前面加this
getters:{
getAge(state){
return state.age+100
},
//调用getters中的函数 这里不要用箭头函数 否则this的指向会发生问题
getAddAge(state){
return state.age + this.getAge
},
//传入数值,找到符合指定值的数据
getUsersById(state){
return (userId)=>state.users.find((item)=>item.id===userId)
}
},
actions:{
}
})
<template>
<div class="app">
<h2>{{name}}</h2>
<h2>{{age}}</h2>
<h2>{{item}}</h2>
<h2>{{getAge}}</h2>
<h2>{{getAddAge}}</h2>
<h2>{{getUsersById(2)}}</h2>
<button @click="changeName">更改姓名</button>
<button @click="reset">重置store</button>
<button @click="patchStore">批量修改数据</button>
<button @click="patchStore2">批量修改但不是全部数据</button>
</div>
</template>
<script setup>
import {
useStore
} from "./store/user.js";
import {
storeToRefs
} from 'pinia'
const store = useStore()
let {
name,
age,
item,
getAge,
getAddAge,
getUsersById
} = storeToRefs(store)
const changeName = () => {
store.name = '李四' //更改state中的数据storeToRefs
store.age = 50
}
const reset = () => {
store.$reset(); //重置$reset
}
const patchStore = () => {
store.$patch({
name: '李四', //批量修改$patch
age: 60
})
}
const patchStore2 = () => {
store.$patch((state) => {
state.item.push({
name: 'shoes',
quantity: 1
})
})
}
</script>
action
//pinia里没有mutations了 所有的同步和异步方法全部放在actions中
用法和vuex中的基本一致