新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Vue新的狀態(tài)管理庫Pinia入門教程
前沿
Vue官方推薦的狀態(tài)管理庫是Vuex,那為什么最近Pinia會(huì)火起來呢,主要在于Vue3推出來的時(shí)候,Vuex對(duì)于Vue3的組合式Api支持的不是特別好,也就是在這個(gè)時(shí)候Pinia出現(xiàn)了,最重要的是,Pinia不但支持Vue3,同時(shí)還支持Vue2,這就厲害了,而且最新Vuex5的特性還是參考的Pinia

專注于為中小企業(yè)提供成都做網(wǎng)站、成都網(wǎng)站制作服務(wù),電腦端+手機(jī)端+微信端的三站合一,更高效的管理,為中小企業(yè)梨樹免費(fèi)做網(wǎng)站提供優(yōu)質(zhì)的服務(wù)。我們立足成都,凝聚了一批互聯(lián)網(wǎng)行業(yè)人才,有力地推動(dòng)了上千企業(yè)的穩(wěn)健成長,幫助中小企業(yè)通過網(wǎng)站建設(shè)實(shí)現(xiàn)規(guī)模擴(kuò)充和轉(zhuǎn)變。
使用教程
官網(wǎng):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',
// 其它配置項(xiàng)
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++
},
},
})
// 在組件中使用
// 導(dǎo)入狀態(tài)
import { useCounterStore } from '@/stores/counter'
export default {
setup() {
// 初始化一個(gè)store實(shí)例
const counter = useCounterStore()
// state更新
counter.count++
// 或者調(diào)用方法更新
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++
}
}
})
// 定義另外一個(gè)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新的狀態(tài)管理庫Pinia入門教程
文章路徑:http://www.dlmjj.cn/article/dhdicpp.html


咨詢
建站咨詢
