安装Pinia
npm install pinia
在main.js里面引入并注册挂载使用
在src下创建一个store inex.js
// index.js
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
//更简洁的的模块化 transferringValuesBetweenComponents simulationModule
//简单定义了两个模块化 也可以在store文件夹下面定义多个js文件
//transferringValuesBetweenComponents 定义了一个模块
export const usePinia = defineStore("transferringValuesBetweenComponents", () => {
const count = ref(1);
const doubleCount = computed(() => {
return count.value * 2
})
function increase() {
count.value++
}
return { count, doubleCount, increase }
})
//simulationModule模拟模块写法
export const simulationModule = defineStore("simulationModule", () => {
const count = ref(0);
const doubleCount = computed(() => {
return count.value * 3
})
function increase() {
count.value += 3
}
return { count, doubleCount, increase }
})
在页面中的使用 先引入 再使用
<template>
<div>
<h3>count:{{ transferringValuesStore.count }}</h3>
<h4>doubleCount:{{ transferringValuesStore.doubleCount }}</h4>
<button @click="transferringValuesStore.increase">调用pinia</button>
</div>
</template>
<script setup>
import { simulationModule } from "../store/index";
const transferringValuesStore = simulationModule();
</script>