vue3中使用pinia
1、 安装引入
npm install pinia
main.ts中挂载
import { createPinia } from 'pinia'
const pinia = createPinia();
app.use(pinia);
2、src下新建 store 文件夹(不同模块建立不同文件,在index.ts中导出)
index.ts
import test from "./test" export default function useStore() { return { TestStore: test(), }; }
test.js (test store)
import { defineStore } from "pinia";
// 用户的类型声明文件
const test = defineStore("test", {
state() {
return {
userName: '甲庚农七一一',
};
},
getters: {
getUserName(state) {
return state.userName.split("").reverse().join("");
}
},
actions: {
setCount(data: string) {
this.userName = data.split("").reverse().join("")
}
}
});
export default test
test.vue 中使用
<template>
<div>{{ TestStore.userName }}</div>
<input type="text" v-model="state.nameValue">
<button @click="nameChange">确定</button>
</template>
<script setup lang="ts">
import {reactive} from 'vue'
import useStore from "@/store";
const { TestStore } = useStore();
const state = reactive({
title: 'hahaha',
nameValue: ''
})
const nameChange = ()=>{
TestStore.setCount(state.nameValue)
}
</script>

浙公网安备 33010602011771号