安装
npm i pinia
main.ts
import './assets/main.css'
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia' // 引入Pinia
// 创建一个应用
const app = createApp(App)
const pina = createPinia()
app.use(pina)
// 挂载整个应用到app容器
app.mount('#app')
'src/store'文件夹——Pinia的实际体现
count.ts
被命名为count是为了和 src/components/Count.vue对应
import {defineStore} from 'pinia'
// useCountStore对应Count 其他的名字也同理
export const useCountStore = defineStore(
// 第一个参数:相当于id值
'count',
// 第二个参数:配置对象
{
// 真正存储数据的地方
state() {
return {
sum:1,
x:'xx',
y:'yy'
}
},
//
actions:{
increment(v) {
this.sum += v // this是useCountStore
}
}
}
)
sentence.ts
import {defineStore} from 'pinia'
// useCountStore对应Count 其他的名字也同理
export const useSentenceStore = defineStore(
// 第一个参数:相当于id值
('sentence'),
// 第二个参数:配置对象
{
state() { // 真正存储数据的地方
return {
sentenceList:[
{id:'1', title:'11'},
{id:'2', title:'22'},
{id:'3', title:'33'},
]
}
}
}
)
Vue插件的Pinia结果
提前准备的效果
Count.vue
<template>
<h2>Sum = {{ countStore.sum }} x = {{ countStore.x }}</h2>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="add">+</button>
<button @click="minus">-</button>
</template>
<script setup lang="ts" name="Count">
import {ref} from "vue";
import {useCountStore} from '@/store/count'
import type { createIncrementalCompilerHost } from "typescript";
const countStore = useCountStore()
let n = ref(0)
function add() {
// 第一种修改方式
// countStore.sum += n.value
// 第二种修改方式
// countStore.$patch(
// {
// sum: 999,
// x:'xxxxx',
// y:'yyyyy'
// }
// )
// 第三章修改方式
// 配合count.ts的action
countStore.increment(n.value)
}
function minus() {
countStore.sum -= n.value
}
</script>
sentence.vue
<template>
<button>get</button>
<li v-for="sen in sentenceStore.sentenceList" :key="sen.id">{{ sen.title }}</li>
</template>
<script setup lang="ts" name="sentence">
import {useSentenceStore} from '@/store/sentence'
const sentenceStore = useSentenceStore()
</script>
App.vue
<template>
<Count/>
<br>
<sentence/>
</template>
<script lang="ts" setup name="App">
import {RouterView, RouterLink} from 'vue-router'
import Count from './components/Count.vue'
import sentence from './components/sentence.vue'
</script>
<style scoped>
/* 可以添加一些样式 */
</style>