import App from './App' //导入pinia import * as Pinia from 'pinia' // #ifndef VUE3 import Vue from 'vue' import './uni.promisify.adaptor' Vue.config.productionTip = false App.mpType = 'app' const app = new Vue({ ...App }) app.$mount() // #endif // #ifdef VUE3 import { createSSRApp } from 'vue' export function createApp() { const app = createSSRApp(App) //创建pinia实例 const pinia=Pinia.createPinia(); //使用pinia app.use(pinia); return { app, Pinia } } // #endif
import {defineStore} from 'pinia' import {ref,computed} from 'vue' const useOneStore=defineStore("color",()=>{ //定义状态 const color=ref('red') const num=ref(0) const str=ref("") //定义设置状态的方法 const setColor=v=>{ color.value=v } const setNum=v=>{ num.value=v } const setStr=v=>{ str.value=v } //导入 return {color,setColor,num,setNum,str,setStr} }) export default useOneStore
在index.vue中使用
<template> <view> <view :style="{'background-color':oneStore.color}"> setup pinia </view> <button @click='oneStore.setColor("#fff")'>白色</button> <button @click='oneStore.setColor("#36f")'>蓝色</button> <button @click='oneStore.setColor("#f36")'>橙色</button> <view>num的值:{{oneStore.num}}</view> <button @click='handleA'>修改num</button> <view>str的值:{{oneStore.str}}</view> <button @click='handleStr'>修改str的值</button> </view> </template> <script setup> import useOneStore from '@/stores/useOneStore.js' const oneStore=useOneStore() const handleA=()=>{ oneStore.setNum(++oneStore.num) } const handleStr=()=>{ oneStore.str="寅春树" } </script>