vuejs怎么结合pinia插件

2024年08月06日 建站教程

vuejs怎么结合pinia插件,下面web建站小编给大家详细介绍一下!

1、安装pinia脚手架

yarn add pinia -S

2、main.js引入

import {createApp} from "vue"
import App from "./app.vue"
import store from "./store/index.js"
const app = createApp(App);
const store = createPinia();
app.use(store).mount("#app")

3、在store文件夹下新建test.js

import {definePinia} from "pinia"
export default testStore = definePinia('testId',{
  state:()=>{
    tname:"test",
    tnum:0,
  },
  getters:{
     changeTnum(){
       console.log("getters")
       this.tnum++;
     }
  },
  actions:{
     addNum(val){
       this.tnum += val
     }
  },
  //持久化存储配置
  presist:{
    enable:true,
    strategies:[
       {
       key:"testId",
       storage:localStorage,
       paths:['tnum']
       } 
    ]
  }
})

4、在store文件夹下新建index.js

import {createPinia} from "pinia"
const store = createPinia();
export default store

5、新建vue组件

<template>
  <div>
    <div> {{tname}}</div>
    <div> {{tid}}</div>
    <div> tnum: {{tnum}}</div>
    <div> {{tchangeNum}}</div>
    <div><button @click="tchangeName">修改</button></div>
    <div> <button @click="treset">重置</button></div>
    <div @click="actionsBtn">actionsBtn</div>
  </div>
</template>
<script setup>
import { storeToRefs } from 'pinia'
import { useStore } from '../store/user'
import { useTest } from '../store/test.js'
const testStore = useTest();
let { tname, tchangeNum, tnum } = storeToRefs(testStore)
</script>
//直接修改数据
tchangeName(){
  tname.value = "测试数据";
  tnum.value++;
}
//当然也可以使用`$path`批量修改
tchangeName(){
  testStore.$path(state=>{
    state.tname = "测试数据";
    state.value = 7;
  })
}

本文链接:http://so.lmcjl.com/news/10128/

展开阅读全文