This is vue3's new state management tool. Simply put, it is equivalent to the previous vuex. It removes Mutations but also supports vue2. It is highly recommended. Because its logo looks like a pineapple, we also call it Big Pineapple.
This is vue3
a new state management tool. Simply put, it is equivalent to the previous vuex
. It removes Mutations
but also supports vue2
is highly recommended. Because its logo looks like a pineapple, we also call it Big Pineapple.
npm i pinia
1, mian.js
introduced pinia
, global registration
import { createApp } from 'vue' import { createPinia } from 'pinia' import App from './App.vue' const app = createApp(App) app.use(createPinia()) app.mount('#app')
2. Create a new index.js
file in the store folder. If you support TS, you can create index.ts
and introduce pinia
into the file for storage. Status
import {defineStore} from 'pinia' export const useUserStore = defineStore("USER",{ state() { return { name: '景天', age: 18, name1: '胡歌', age1: 36 } }, // 和vuex一样 getters: { }, // 和vuex一样 actions: { setAge() { this.age-- } } })
3. The page uses the status The above is the detailed content of How to use Vue3 pinia state management tool. For more information, please follow other related articles on the PHP Chinese website!<template>
<div>正常取值</div>
<div>{{User.name}}</div>
<div>{{User.age}}</div>
<div>解构取值</div>
<div>{{name}}</div>
<div>{{age}}</div>
<div>解构取值转ref</div>
<div>{{name1}}</div>
<div>{{age1}}</div>
<button @click="change1">change1</button>
<button @click="change2">change2</button>
<button @click="change3">change3</button>
<button @click="change4">change4</button>
<button @click="change5">change5</button>
<div>
<button @click="handleReset">重置</button>
</div>
</template>
<script setup lang="ts">
import { storeToRefs } from 'pinia';
import { useUserStore } from './store';
// 获取store中的值
let User = useUserStore()
// 通过ES6的结构取值,但是这个值不是响应式的
let {name,age} = User
// 通过pinia自带的方法,转换成ref,就是响应式的了
let {name1,age1} = storeToRefs(User)
// 改变store中值的方式有五种
// 方式一
function change1() {
User.age++
}
// 方式二,可一次性修改多个值,对象的形式
function change2() {
User.$patch({
name: '雪见',
age: 17
})
}
// 方式三,可一次性修改多个值,函数的形式
function change3() {
User.$patch((state) => {
state.name = '徐长卿'
state.age = 19
})
}
// 方式四,哪怕修改一个值,也要传所有值???
function change4() {
User.$state = {
name: '茂茂',
age: 16,
name1: '李逍遥',
age1: 18
}
}
// 方式五,借助actions
function change5() {
User.setAge()
//也可以传参
// User.setAge(999)
}
// 重置数据
function handleReset() {
User.$reset()
}
</script>
<style>
</style>