Vue传值Pinia的使用

Pina官网 Pinia 是 Vue 的存储库,它允许您跨组件/页面共享状态。

main.js文件

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

//import {storeReset} from './stores/counter'

const app = createApp(App)
const store = createPinia();

//reset使用是需要添加
//Uncaught Error: 🍍: Store "counter" is built using the setup syntax and does not implement $reset().
store.use(({store})=>{
    const initialState = JSON.parse(JSON.stringify(store.$state));
    store.$reset = ()=>{
        store.$state = JSON.parse(JSON.stringify(initialState));
    }
    
});

app.use(store)

app.mount('#app')

App.vue文件


<script setup>
import { storeToRefs } from "pinia"
import {useCounterStore} from './stores/counter'
import {MObj} from './stores/mystore'
import ChildA from './components/ChildA.vue';

storeToRefs(useCounterStore())	//响应处理,其他页面也会实时更新

const counter = useCounterStore();
const MStoreObj = MObj();

//订阅修改
counter.$subscribe((mutation, state)=>{
  console.log("some value change");
  console.log(mutation, state)
})


function add()
{
  counter.count++;
}

function reset()
{
  //counter.$state = {count:0};
  counter.$reset();
}

function add_age()
{
  MStoreObj.add_age(1);
}

function change_name()
{
  console.log("2222");
  MStoreObj.changename("new name ");
}

</script>

<template>
    <h2>pinia的使用</h2>
    <p> count : {{ counter.count }} </p>
    <p> doubleCount : {{ counter.doubleCount }} </p>
    <button @click="counter.increment">add func</button>
    <button @click="add">add count</button>
    <button @click="reset">reset count</button>
    <br/>
    <br/>
    <div> name:  {{ MStoreObj.name }} age : {{ MStoreObj.age }}</div>
    <button @click="add_age">add age</button>
    <button @click="change_name"> change_name</button>
    <br/>
    <ChildA></ChildA>
</template>

<style scoped>

</style>

counter.js

import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  const doubleCount = computed(() => count.value * 2)
  function increment() {
    count.value++
  }

  return { count, doubleCount, increment }
})

mystore.js文件

import { ref, computed } from 'vue'
import { defineStore, mapActions } from 'pinia'

export const MObj = defineStore("myobj",{

    state : ()=>{
        return {
            name: "a",
            age: 0
        }
    },

    actions : {

        add_age(num){
            this.age+=num;
        },

        changename(newname)
        {
            this.name = newname;
        }
    }
})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值