Pinia-vue3-demo教程

//main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
// import store from './store'

import {createPinia} from 'pinia'

// 安装pinia插件实现持久化存储,根据需求安装,不需要则不用安装
// npm i pinia-plugin-persist --save
// 引入插件
import piniaPluginPersist from 'pinia-plugin-persist'
// 使用插件
const pinia = createPinia()
pinia.use(piniaPluginPersist)

createApp(App).use(pinia).use(router).mount('#app')
//    store/index.js

import { defineStore } from 'pinia'

export const useStore = defineStore('storeId',{
  //类似data
  state: ()=>{
    return {
      num:1,
      name:'张三',
      arr:[],
      count:0
    } 
  },
  //类似计算属性
  getters: {
    changeNum(){
      return this.num +100
    }
  },
  //类似方法
  actions: {
    upNum(val){
      this.num +=val
    },
    addarr(obj){
      this.arr.push(obj)
      this.count = this.arr.length
    }
  },
  //开启数据缓存,不需要则不用下方代码
  persist:{
    enabled:true,
    strategies:[
      {
        key:'my_user',//储存的key
        storage:localStorage,//储存方式
        paths:['num']//储存数据,不要此项则储存所有数据
      }
    ]
  }
})
//vue页面

<template>
  <div class="hello">
    {{msg}}
  </div>
  <div>
    {{name}}------{{num}}
    <br>
    <button @click="btn">按钮</button>
    <br>
    <button @click="addbtn">add</button>
    <br>
    {{changeNum}}
    <hr>
    数组内容:
    <div v-for="(item,index) in arr" :key="index">
      {{item}}
    </div>
    数组长度:
    <div>{{count}}</div>
    <button @click="addarrbtn">addarrbtn</button>
  </div>
</template>

<script setup>
  import {ref} from 'vue'
  //引入store/index.js定义的实例
  import {useStore} from '../store'
  //将实例转为动态
  import { storeToRefs } from 'pinia';
  
  //储存实例
  let store  = useStore()
  //将实例转为动态对象并结构出来,只能结构state和getters中的内容,不需要结构actions中的方法
  let {name,num,changeNum,arr,count} = storeToRefs(store)
  console.log(name,num)
  
  const btn = ()=>{
    //直接修改state中的值
    name.value='李四'
  }
  const addbtn  = ()=>{
    //调用actions中的方法,修改state中的值
    store.upNum(2)
  }
  const addarrbtn = ()=>{
    var obj = {
      name:'aaa',
      age:18
    }
    store.addarr(obj)
  }

  // const  msg = ref('aaa')

// 监听数据变化
watch(() => store.chooseitem, (newValue, oldValue) => {
  console.log(newValue)
  console.log(oldValue)
  store.setchooseitem(newValue,oldValue)
});
// 监听pinia中触发action方法
store.$onAction(({ name, store, args }) => {
  console.log(`Action ${name} called on store ${store.$id} with args:`, args)
})
</script>

<style scoped >

</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

T-小丑

需要什么demo可以留言

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值