国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

Vuex 單狀態(tài)庫與多模塊狀態(tài)庫詳解

2024-05-06 15:27:21
字體:
供稿:網(wǎng)友

什么情況下使用vuex

Vuex 是一個專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式。它采用集中式存儲管理應(yīng)用的所有組件的狀態(tài),如果您不打算開發(fā)大型單頁應(yīng)用,使用 Vuex 可能是繁瑣冗余的。如果您需要構(gòu)建是一個中大型單頁應(yīng)用,您很可能會考慮如何更好地在組件外部管理狀態(tài),Vuex 將會成為自然而然的選擇。

之前在做旅游頁的時(shí)候?qū)?Vuex 進(jìn)行了簡單的了解。近期在做 Vue 項(xiàng)目的同時(shí)重新學(xué)習(xí)了 Vuex 。本篇博文主要總結(jié)一下 Vuex 單狀態(tài)庫和多模塊 modules 的兩類使用場景。

本篇所有代碼是基于 Vue-Cli 3.x 版本的腳手架工具進(jìn)行編寫的。

vuex 單狀態(tài)庫 Demo

這是一個僅有單個 Vuex store 狀態(tài)庫的 Demo。當(dāng)項(xiàng)目中使用一個 Vuex 狀態(tài)庫就已經(jīng)足夠的時(shí)候,可以使用這種方式。

本 Demo 使用了一個 increment 與 decrement 的 增 / 減 事件來體現(xiàn) store 數(shù)據(jù)的變化。

store.js

由于狀態(tài)庫是單一的,僅有一個 store.js 文件管理狀態(tài)庫。在該文件中一開始進(jìn)行 import 的引入,然后使用 Vue.use(Vuex) 使用 Vuex,之后分別定義 state、mutations 和 actions,并通過 export default new Vuex.Store({state, mutations, actions}) 模塊化。

// store.jsimport Vue from 'vue'import Vuex from 'vuex'Vue.use(Vuex)const state = { count: 1}const mutations = { increment(state) {  state.count ++ }, decrement(state) {  state.count -- }}const actions = { increment:({commit}) => {  commit('increment') }, decrement:({commit}) => {  commit('decrement') }}export default new Vuex.Store({state, mutations, actions})

main.js

在入口文件 main.js 中通過 import 引入 store,并注冊到 Vue 的實(shí)例上。

import Vue from 'vue'import App from './App.vue'import store from './store'// Vue-Cli 3.xnew Vue({ render: h => h(App), router, store}).$mount('#app')// Vue-Cli 2.x// new Vue({//  el: '#app',//  router,//  store,//  components: { App },//  template: '<App/>'// })

使用 $store

在相應(yīng)的組件中如下引入并在 methods 中使用 mapActions。

<template> <div class="vuex">  Vuex 全局 Store count {{$store.state.count}}  <button type="button" name="button" @click="increment">加</button>  <button type="button" name="button" @click="decrement">減</button> </div></template><script>import { mapActions } from 'vuex'export default { methods: mapActions([  'increment',  'decrement' ])}</script><style scoped></style>

Demo

關(guān)于單狀態(tài)庫的 Demo 請參考此 github

Github Demo 

vuex 多模塊狀態(tài)庫 Demo

當(dāng)項(xiàng)目變得非常龐大,單個 store 無法滿足需求的時(shí)候,可以通過多模塊狀態(tài)庫管理多個 store,將各類狀態(tài)分類進(jìn)行維護(hù)。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 中卫市| 泉州市| 弥渡县| 富民县| 光泽县| 阿合奇县| 波密县| 绥棱县| 信阳市| 措勤县| 连云港市| 逊克县| 定陶县| 云浮市| 合江县| 洪湖市| 呼玛县| 金沙县| 确山县| 建平县| 新平| 大连市| 剑阁县| 桓仁| 青田县| 乌拉特后旗| 安溪县| 福建省| 漳州市| 涿鹿县| 崇明县| 山东| 新和县| 车致| 阿尔山市| 昭觉县| 民和| 奉新县| 当阳市| 奉新县| 大同市|