vue3+ pinia 的初实用

固定不变的 : stores/index.js

import { createPinia } from "pinia"

const pinia = createPinia()

export default pinia

 

main.js


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

createApp(App).use(pinia).mount('#app')

 

定义 : stores/counter.js


import { defineStore } from "pinia";

// 定义关于counter的store
// 参数1 : 这个store的id 
// 参数2 : 对象 => 存数据
// 会返回一个函数 : 命名为 use+id
const useCounter  =  defineStore("counter",{
    state:()=>({
        count:99
    }),
    getters:{

    },
    action:{

    }
})

export default useCounter 

 

使用 : 

<template>
  <div class="id">
    <!-- 原本版本 -->
    count : {{ counterStore.count }}

    <!-- 简化版本-->
    count : {{ count }}

    <button @click="btn">+1</button>
  </div>
</template>

<script setup>
import useCounter from './stores/counter';
import { toRefs } from 'vue';
const counterStore = useCounter()

// 简化版本
const { count } = toRefs(counterStore)

const btn = ()=>{
  counterStore.count++
}

</script>

<style>

</style>

 

posted @ 2022-08-30 16:08  杨建鑫  阅读(61)  评论(0编辑  收藏  举报