Vue——pinia 状态管理器

1. 安装pinia

yarn add pinia
# 或者使用 npm
npm install pinia
# 或者使用 cnpm
cnpm install pinia

2. 项目初始化pinia

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

const pinia = createPinia()
const app = createApp(App)

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

3. 创建一个计数器的管理器counter.ts

import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0
  }),
  actions: {
    addCount() {
      this.count++
    }
  },
  getters:{
    countDouble(state){
      return state.count * 2 
    }
  }
})

4. setup中使用

<script setup lang="ts">
import { useCounterStore } from '../stores/counter'

const countStore = useCounterStore()
</script>

<template>
  <div>
    <div>count:{{countStore.count}}</div>
    <button @click="countStore.addCount()">增加</button>
  </div>
</template>

默认情况下,你可以通过 store 实例访问 state,直接对其进行读写

const countStore = useCounterStore()

//可读写
countStore.count++
//重置 state ,如果使用Setup函数 创建的管理器,该方法无效
countStore.$reset()
//$patch函数可以同一时间更改多个属性
countStore.$patch({count:0,name:'小明'})
//或
countStore.$patch((state) => {
  state.count = 0
  state.name = '小明'
})

你可能感兴趣的:(Vue,vue.js,javascript,前端)