可视化创建的项目自带安装pinia,项目中可以直接用,cli脚手架安装的需要npm安装pinia
1.可视化项目使用pinia
在main.js引入并注册pinia
import App from './App'
import { createSSRApp } from 'vue'
import * as Pinia from 'pinia'
export function createApp() {
const app = createSSRApp(App)
// 注册pinia
app.use(Pinia.createPinia())
return {
app,
Pinia
}
}
在根目录下新建store文件,新建子文件counter.js
import {defineStore} from 'pinia'
// name:counter,是store的名称,需要保证唯一性,或者唯一的ID
export const useCounterStore=defineStore('counter',{
state:()=>{
return{
count:700,
}
},
actions:{
// 同步
increment(){
this.count++
},
decrement(){
this.count--
}
}
})
在项目中使用pinia
<template>
<view>
<view class="">
{{count}}
</view>
<button @click="addCount">count++</button>
<button @click="subCount">count--</button>
</view>
</template><script setup>
import {storeToRefs} from 'pinia'
import {useCounterStore} from '@/store/counter.js'
const counterStore=useCounterStore()
// storeToRefs获取pinia的响应式对象
const {count}=storeToRefs(counterStore)
function addCount(){
counterStore.increment()
}
function subCount(){
counterStore.decrement()
}
</script><style>
</style>