1.在终端输入一下命令:
npm install pinia
2.接着我们对他做这个使用:在根目录新建一个store 文件夹
3.新建index.ts ,在这个文件里写入下面代码
//1.引入pinia
import {createPinia} from 'pinia'
//2.创建 pinia
const pinia =createPinia()
//3.再把这个pinia 导出出去
export default pinia
4.倒出之后让pinia 生效,在mian.ts
import {createApp} from 'vue'
import App from './App.vue'
import pinia from './store' //导入
const app=createApp(App)
app.use(pinia) //挂载
app.mount('#app')
5.这些数据都是一个个保存在store 里面的:
例子:新建文件counter.ts
//1.创建store import { defineStore } from 'pinia' //2.第一个参数是id,传入一个字符串,第二个参数是是对象 const useCounterStore=defineStore("counter",{ state:()=>({ counter:100 }), getters:{ doubaleCounter(state){ return state.counter*2 } }, actions:{ changeCounteAction(newCounter:number){ this.counter=newCounter } } }) //3.导出 export default useCounterStore
假如现在main.ts 里面使用:
<template> <div class="mian"> <h2>main:{{counterStore.counter}}-{{counterStore.doubaleCounter}}</h2> <button @click="changeCounter">修改counter</button> </div> </template> <script setup lang="ts"> import useCounterStore from '@/store/counter' const counterStore=useCounterStore() changeCounter(){ //调用changeCounteAction counterStore.changeCounteAction(999) } </script>