vue3:16、Pinia的基本语法

选项式APi 

组合式API 

 

src/store/counter.js

import { defineStore } from "pinia";
import { computed, ref } from "vue";

export const userCounterStore = defineStore("counter",()=>{
    //声明数据 state - count
    const count = ref(100)

    //声明操作数据的方案 action (普通函数)
    function addCount(){
        count.value++
    }
    function subCount(){
        count.value--
    }
    //声明基于数据派生的计算属性 getters
    const double = computed(() => count.value*2)

    //声明数据 state -msg
    const msg = ref('你好 pinia')

    return {
        count,
        double,
        addCount,
        subCount,
        msg
    }
})

 根组件

<script setup>
import Son1Com from '@/components/Son1Com.vue';
import Son2Com from '@/components/Son2Com.vue';
import {userCounterStore} from '@/store/counter'
const counterStore = userCounterStore()
</script>
<template>
  
 <h3>
  APP.vue根组件
  <br>
    {
   
   { counterStore.count }}
    <br>
    {
   
   { counterStore.msg }}
 </h3>
 <Son1Com></Son1Com>
 <Son2Com></Son2Com>
</template>

 子组件

<script setup>
import { userCounterStore } from '@/store/counter'
const counterStore = userCounterStore()
</script>
<template>
  <div>Son2 {
   
   { counterStore.count }} - {
   
   { counterStore.double }}</div>
  <button @click="counterStore.subCount">-</button>
</template>

猜你喜欢

转载自blog.csdn.net/qq_37899792/article/details/132743242