Pinia使用案例

2023-10-24 15:04:27 浏览数 (1)

前言

大家好 我是歌谣 今天给大家带来Pinia的讲解

安装vite程序

yarn create vite

main.ts

代码语言:javascript复制
import { createApp } from 'vue'
import './style.css'
import {createPinia} from "pinia"
import App from './App.vue'
const pinia=createPinia()
createApp(App).use(pinia).mount('#app')

HelloWorld.vue

代码语言:javascript复制
<script setup lang="ts">
import { ref } from 'vue'
import { useCounterStore,useMsgStore } from '../store/index';
defineProps<{ msg: string }>()
const counter=useCounterStore()
const useMsg=useMsgStore()
const count = ref(0)
</script>


<template>
  <h1>{{ msg }}</h1>


  <div class="card">
    <h2>{{ useMsg.msg }}</h2>
    <button type="button" @click="counter.increment">count is {{ counter.count }}</button>
    
  </div>


</template>


<style scoped>
</style>

index.ts

代码语言:javascript复制
import { defineStore } from "pinia";
import {ref} from 'vue'
export const useCounterStore=defineStore('counter',{
    state:()=>{
        return {count:0}
    },
    getters:{
        double:(state)=>state.count*2
    },
    actions:{
        increment(){
            return this.count  
        }
    }
})


export const useMsgStore=defineStore('msg',()=>{
    const msg=ref('geyao')
    function changeMsg(){
        msg.value ='world'
    }
    return {msg,changeMsg}
})

运行结果

0 人点赞