
前沿
使用教程
1、安装
2、vue中引入
3、基本使用
4、也可以像vuex一样使用
为什么最近Pinia会火起来呢,主要在于Vue3推出来的时候,Vuex对于Vue3的组合式Api支持的不是特别好,也就是在这个时候Pinia出现了。
前沿Vue官方推荐的状态管理库是Vuex,那为什么最近Pinia会火起来呢,主要在于Vue3推出来的时候,Vuex对于Vue3的组合式Api支持的不是特别好,也就是在这个时候Pinia出现了,最重要的是,Pinia不但支持Vue3,同时还支持Vue2,这就厉害了,而且最新Vuex5的特性还是参考的Pinia
使用教程官网:https://pinia.vuejs.org/
github地址:https://github.com/vuejs/pinia
1、安装npm install pinia -S
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']),
  },
}
好了,Pinia的入门教程就讲到这,是不是语法更加简洁
到此这篇关于Vue新的状态管理库Pinia入门教程的文章就介绍到这了,更多相关Vue Pinia内容请搜索易知道(ezd.cc)以前的文章或继续浏览下面的相关文章希望大家以后多多支持易知道(ezd.cc)!














