vue3 pinia的使用

90 阅读1分钟

像vue2 一样 在vue3 使用setup + ts + pinia

傻瓜四步操作

  1. main.ts
// 引入store
import store from '@/stores'

const app = createApp(App)

app.use(store)
app.use(router)

app.mount('#app')
  1. stores文件夹下 创建 index.tsc 文件
import { createPinia } from 'pinia'     // 引入

const store =createPinia()              // 创建store

export default store                    // 导出 --main.JS 中使用
  1. stores文件夹下 创建 分支文件 counters.ts 文件


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

// 组合式
export const useCounterStore = defineStore('counter', () => {
    // 通过 ref reactive 定义state
    const num = ref(0)
    const user = reactive({ age: 22, name: '希望' })
    // 通过computed 定义 getters
    const doubleNum = computed(() => {
        return num.value*2
    })
    // 通过methods 定义 actions
    const ChangeNumAndUser = ()=>{
        return  setTimeout(()=>{
                        num.value = 88
                        user.name = '新希望'
                       },1000)
    }
    return { num, user ,doubleNum ,ChangeNumAndUser }
})
import { defineStore } from 'pinia'
//  选项式 导出                        // 第一个参数 唯一id 名  第二个参数 函数 或 对象
export const useCounterStore = defineStore('counter', {
    state (){
        return {
            num: 1 ,
            user: {
                age: 22,
                name: '希望'
            }
        }
    },
    getters: {
        doubleNum ():number{
            return this.num*2
        }
    },
    actions: {
        // 书写同步 异步代码
        ChangeNumAndUser (){
           setTimeout(()=>{
            this.num = 88
            this.user.name = '新希望'
           },1000)
        }
    }
})
  1. Program.vue 文件使用

    <template>
      <div>
        <p>{{ counterStore.num }} --计算属性{{ doubleNum }}</p>
        <button @click="num++">counterStore --{{ num }}</button>
        <p>{{ user }}</p>
        <button @click="counterStore.$reset()">重置状态</button>
        <button @click="UpdateState">批量修改状态</button>
      </div>
    </template>
    <script lang="ts"  setup>
    
    import { useCounterStore } from '@/stores/counters'
    import { storeToRefs } from 'pinia';
    import { watchEffect } from 'vue';
    
    const counterStore = useCounterStore()
    const {ChangeNumAndUser} = counterStore     // 解构  store 的方法
    const { num, user,doubleNum } = storeToRefs(counterStore) // (state,getters)响应式解构 objectRefImpl
    
    // 批量修改状态 的多种方案
    const UpdateState = () => {
      // user.value.name = '重生'
      // counterStore.num = 20
      
      // $path可以写成 对象 或 函数
      // counterStore.$patch({
      //   num: 100,
      //   user: {
      //     age: 33
      //   }
      // })
      // 使用 store的方法
      ChangeNumAndUser()
    }
    // 直接 调用store 的actions 方法
    // counterStore.ChangeNumAndUser()
    // 监听
    watchEffect(() => {
      console.log(num.value);
    
    })
    </script>
    
    <style lang="scss" scoped></style>