自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Vue新的狀態(tài)管理庫Pinia入門教程

開發(fā) 項目管理
為什么最近Pinia會火起來呢,主要在于Vue3推出來的時候,Vuex對于Vue3的組合式Api支持的不是特別好,也就是在這個時候Pinia出現(xiàn)了。

前沿

Vue官方推薦的狀態(tài)管理庫是Vuex,那為什么最近Pinia會火起來呢,主要在于Vue3推出來的時候,Vuex對于Vue3的組合式Api支持的不是特別好,也就是在這個時候Pinia出現(xiàn)了,最重要的是,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', {
// 狀態(tài)值定義
state: () => {
return { count: 0 }
},
// 狀態(tài)更改方法定義
actions: {
increment() {
this.count++
},
},
})

// 在組件中使用
// 導入狀態(tài)
import { useCounterStore } from '@/stores/counter'

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

// state更新
counter.count++

// 或者調用方法更新
counter.increment()
},
}

4、也可以像vuex一樣使用

const useCounterStore = defineStore('counter', {
// 狀態(tài)值
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的入門教程就講到這,是不是語法更加簡潔

責任編輯:姜華 來源: 今日頭條
相關推薦

2022-05-23 08:59:02

piniavue插件

2021-12-16 08:47:56

Vue3 插件Vue應用

2011-07-04 11:38:06

MySQL

2022-02-18 09:39:51

Vue3.0Vue2.0Script Set

2025-03-03 11:31:05

2022-10-09 09:18:01

ColadaPinia

2024-11-12 15:46:37

2010-08-03 13:06:15

Flex Builde

2013-08-29 14:12:52

Storm分布式實時計算

2009-07-08 15:12:48

Java Servle

2014-05-26 15:35:55

Web組件Web Compone

2021-07-16 22:49:50

PiniaVuex替代品

2010-03-12 14:04:32

Python入門教程

2022-07-12 08:27:18

Zadig開源

2022-07-21 11:58:12

Docker

2018-07-05 11:30:56

數據庫瀏覽器IndexedDB

2010-05-21 12:50:45

Subversion快

2011-07-21 10:29:18

iPhone 開發(fā)

2010-07-27 15:53:15

2010-08-03 14:37:30

Flex入門教程
點贊
收藏

51CTO技術棧公眾號