uniapp在vue3中使用Pinia

image.png

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

image.png

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>

image.png

复制内容


评论


乖,登录后才可以留言! 登录

Copyright © 2020-2023 春藤技术,春藤建站 All Rights Reserved
备案号:豫ICP备20020705号 公网安备 51LA统计
0.220251s