Vue状态管理库Pinia教程

发布时间:2022-06-20浏览次数:0

支持注册ChatGPT Plus的OneKey虚拟卡
绑定Apple Pay、Google Pay、支付宝和微信支付进行日常消费

注册和了解更多 ->

silver

使用教程

官网:https://pinia.vuejs.org/

github地址:https://github.com/vuejs/pinia1.2.3.

1、安装

复制

npm install pinia

2、vue中引入

// Vue3中引入使用
import { createPinia } from 'pinia'

app.use(createPinia())


//Vue2中引入使用
import { createPinia, PiniaVuePlugin } from 'pinia'

Vue.use(PiniaVuePlugin)
const pinia = createPinia()

new Vue({
  el: '#app',
  // 其它配置项
  pinia,
})

3、基本使用

// 定义store
// stores/counter.js
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  // 状态值定义
  state: () => {
    return { count: 0 }
  },
  // 状态更改方法定义
  actions: {
    increment() {
      this.count++
    },
  },
})

// 在组件中使用
// 导入状态
import { useCounterStore } from '@/stores/counter'

export default {
  setup() {
    // 初始化一个store实例
    const counter = useCounterStore()

    // state更新
    counter.count++
    
    // 或者调用方法更新
    counter.increment()
  },
}

4、也可以像vuex一样使用

const useCounterStore = defineStore('counter', {
  // 状态值
  state: () => ({ count: 0 }),
  // getter值
  getters: {
    double: (state) => state.count * 2,
  },
  // actions方法
  // 注意pinia里没有mutation
  actions: {
    increment() {
      this.count++
    }
  }
})

// 定义另外一个store
const useUserStore = defineStore('user', {
  // ...
})

export default {
  // computed里引入使用state里的值
  computed: {
    ...mapStores(useCounterStore, useUserStore)
    ...mapState(useCounterStore, ['count', 'double']),
  },
  // methods里使用action
  methods: {
    ...mapActions(useCounterStore, ['increment']),
  },
}
字节笔记本扫描二维码查看更多内容