安装
pnpm i pinia
项目引入store
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from "pinia"
const pinia = createPinia();
const app = createApp(App);
app.use(pinia)
app.mount("#app")
使用store
解构使store数据失去响应式(storeToRefs)
<script setup>
import { storeToRefs } from "pinia"
import { firstStore } from "./store/index"
const store = firstStore()
const { a } = storeToRefs(store);
const handleClick = () => {
store.a++;
}
</script>
<template>
<h1>hello,pinia</h1>
<h3>{{store.a}}</h3>
<button @click="handleClick">点击+1</button>
<hr>
<h3>{{a}}</h3>
</template>
修改状态数据
- 直接在组件内修改store
- 写进actions中
export const firstStore = defineStore("first", {
state: () => {
return {
a: 1,
b: 2
}
},
getters: {},
actions: {
changeA() {
this.a++;
}
}
})
3.使用$patch
const handleClick = () => {
store.$patch((state) => {
state.a++
})
}
getters使用
export const firstStore = defineStore("first", {
state: () => {
return {
a: 1,
b: 2
}
},
getters: {
doubleA() {
return this.a * 2
}
},
actions: {
changeA() {
this.a++;
}
}
})
store互相调用
import { defineStore } from "pinia"
import { course } from './course';
export const firstStore = defineStore("first", {
state: () => {
return {
a: 1,
b: 2
}
},
getters: {
doubleA() {
return this.a * 2
}
},
actions: {
changeA() {
console.log(course().name)
this.a++;
}
}
})