美文网首页
pinia学习

pinia学习

作者: 回不去的那些时光 | 来源:发表于2023-03-31 11:28 被阅读0次

简介

pinia 是 vuex 的替代,用法比 vuex 更简单,vue2、vue3 中都可以使用

案例

// counter.ts
import { defineStore } from 'pinia';

/**
 * defineStore
 * 第一个参数是一个独一无二的名字
 * 第二个参数可接受两类值:Setup 函数或 Option 对象
 * store命名最好以 use 开头
 */
export const useCounterStore = defineStore('counter', {
    // state 需要接收一个函数
    state: () => {
        return {
            count: 0
        }
    },
    getters: {
        double: (state) => state.count * 2
    },
    actions: {
        increment() {
            this.count++
        }
    }
})
// main.ts
import { createApp } from 'vue'
import { createPinia }  from 'pinia'
import App from './App.vue'
// 创建pinia
const pinia = createPinia()
const app = createApp(App)
// 将pinia注入项目中
app.use(pinia);
app.mount('#app')
<script lang="ts" setup>
import { useCounterStore } from '../store/counter';
// 调用得到对应的 store
const counter = useCounterStore();
const handleIncrement = () => {
    counter.increment();
}
</script>

<template>
    home - {{ counter.count }} - {{ counter.double }}
    <br />
    <button @click='handleIncrement'>增加</button>
</template>

相关文章

网友评论

      本文标题:pinia学习

      本文链接:https://www.haomeiwen.com/subject/vzccddtx.html