VueX學(xué)習(xí)之modules和namespacedVueX詳細(xì)教程
一、今天主要解決
什么是vuex?
為什么要用到vuex?
基礎(chǔ)用法?
二、初步認(rèn)識(shí)Vuex
2.1、父子通信,兄弟間通信局限性
父子通信,兄弟間通信
我們都知道,但是有復(fù)雜的項(xiàng)目,可能會(huì)嵌套很多層
,這樣一層一層的傳值,很麻煩!不光是對(duì)代碼質(zhì)量造成了影響,也對(duì)代碼運(yùn)行的性能造成了影響,甚至?xí)斐呻y以排查的bug。
2.2、講個(gè)例子
小朋友想要零花錢(qián),會(huì)先和媽媽要
,媽媽沒(méi)有,就去和爸爸要
,爸爸把零花錢(qián)給了媽媽
,媽媽再給了小朋友。
這個(gè)就很麻煩了,解決辦法,不如直接爸爸把零花錢(qián)放在一個(gè)指定的位置
,誰(shuí)要,誰(shuí)就去那個(gè)位置拿
2.3、vuex
vuex就是那個(gè)指定的地方,官方給起了個(gè)很專(zhuān)業(yè)的名字,叫:狀態(tài)管理模式,說(shuō)白了,就是一個(gè)統(tǒng)一存放狀態(tài)的地方,誰(shuí)用里邊的值都可以取到,無(wú)論頁(yè)面的層次多深,不用擔(dān)心拿不到的問(wèn)題,這樣解決復(fù)雜通信或傳值的問(wèn)題就很方便了。
三、引入vuex
3.1、安裝
//vue2 npm install --save vuex@3 //vue3 npm install --save vuex
3.2、編寫(xiě)store的js文件
在src目錄下創(chuàng)建一個(gè)文件夾統(tǒng)一取名為 store
在store中創(chuàng)建index.js
新建的index.js中有如下代碼:
import Vue from 'vue' import vuex from 'vuex' Vue.use(vuex) export default new vuex.Store({ state: {}, mutations: {}, getters: {}, actions: {}, modules: {} })
3.2、引入
import store from './store' new Vue({ store, render: h => h(App), }).$mount('#app')
四、各個(gè)模塊介紹
4.1、 state
export default new vuex.Store({ // 手動(dòng)定義一些數(shù)據(jù) state:{ a: 10 } })
接下來(lái)我們?cè)诮M件中獲取并使用一下這個(gè)公共的數(shù)據(jù)
<template> <div> {{$store.state.a}} // 頁(yè)面中打印出10 </div> </template>
4.2、mutations
主要用于修改state中的數(shù)據(jù)
參數(shù)一: state對(duì)應(yīng) state對(duì)象
參數(shù)二: 形參- 需要傳入的參數(shù),可有可無(wú)
語(yǔ)法: mutations:{‘mutations名’:funtion(state,形參) }
例子: 在state中a = 10 , 我們定義一個(gè)mutations方法 對(duì)state中的a的值進(jìn)行修改
export default new vuex.Store({ state: { a: 10 }, mutations: { state.a += 1 // a+1 }, })
接下來(lái)在App.vue中我們寫(xiě)一個(gè)button按鈕用來(lái)點(diǎn)擊并調(diào)用這個(gè)方法 點(diǎn)一次觸發(fā)一次 讓a的值每次加一
<template> <div> {{$store.state.a}} // 點(diǎn)擊一次 就調(diào)用一次 進(jìn)行+1 <button @click="$store.commit('add')">a+1</button> </div> </template>
- 在模板中: $store.commit(‘mutations名’)
- 在組件中: 要加this調(diào)用, this.$store.commit(‘mutations名’)
4.3、getters
- 語(yǔ)法: getters:{ ‘getters名’,function(state,形參)},用法和mutations差不多,
- getters的作用是用于計(jì)算數(shù)據(jù)得到計(jì)算后的新的數(shù)據(jù) 類(lèi)似于computed計(jì)算數(shù)據(jù)
- 示例: 例如在state中有一個(gè)值為b:[1,2,3,4,5],
用getters對(duì)這個(gè)數(shù)據(jù)進(jìn)行計(jì)算 然后打印到頁(yè)面中,具體代碼如下:
getters: { sum: function (state) { return state.b.reduce((temp, item) => temp + item, 0) } }
在頁(yè)面中渲染出來(lái){{$store.getters.sum}} // 15
4.4、actions
語(yǔ)法:
actions:{ ‘action名’,function(context,形參)}
context其實(shí)就是對(duì)應(yīng)的state .
- actions用于發(fā)起異步的請(qǐng)求,可以在actions中用axios發(fā)起數(shù)據(jù)請(qǐng)求,獲取數(shù)據(jù)
繼續(xù)看示例代碼:
// state:{ book:[ ] }, mutations:{ updateBook:function(state,newbook){ state.book = newbook } } actions: { getBooks: function (context) { axios({ url: 'https://www.fastmock.site/mock/37d3b9f13a48d528a9339fbed1b81bd5/book/api/books', method: 'get' }).then(res => { console.log(res); context.commit('updateBook', res.data.data) }) } }
注意: 在state中我定義了一個(gè)數(shù)組 book:[ ]用來(lái)接收獲取到的數(shù)據(jù) , 接收到數(shù)據(jù)res后, 想賦值給book數(shù)組, 但是要記住不能直接進(jìn)行賦值
,必須要在mutations中一個(gè)一個(gè)賦值的函數(shù), 在actions獲取到數(shù)據(jù).調(diào)用mutations中的函數(shù),進(jìn)行賦值.
接著組件中寫(xiě)一個(gè)button按鈕用來(lái)測(cè)試 觸發(fā)actions發(fā)起axios請(qǐng)求獲取數(shù)據(jù),并賦值給book數(shù)組
調(diào)用actions的方式:
- 模塊中: $store.dispatch(‘actions名’)
- 組件中: this.store.dispatch(‘actions名’)
<template> <div> // 點(diǎn)擊 觸發(fā)actions 并發(fā)起axios請(qǐng)求數(shù)據(jù) <button @click="$store.dispatch('getBooks')">獲取數(shù)據(jù)</button> {{$store.state.book}} // 打印獲取到的數(shù)據(jù) </div> </template>
4.5、modules
modules中命名空間
默認(rèn)是namespaced: 為false ,
設(shè)置true后,在組件中使用拆分到modules的數(shù)據(jù)和方法要加"模塊名"
語(yǔ)法:
modules:{ ‘模塊名’:{state{},mutations:{},getters:{},actions:{} }}
作用
modules用來(lái)拆分index.js中的代碼, 減少index.js中代碼的繁多和體積,讓index.js中更簡(jiǎn)潔,把相同的需要的數(shù)據(jù)和方法都提取到同一個(gè)js中
前提
在store文件中新建modules文件,把state中book數(shù)組和mutations中修改book的方法,以及actions中獲取數(shù)據(jù)的相關(guān)代碼剪切到modules文件中的新建的allBook.js文件中
import axios from 'axios' export default { state: { b: [1, 2, 3, 4, 5], book: [] }, mutations: { updateBook: function (state, newbook) { state.book = newbook } }, getters: { sum: function (state) { return state.b.reduce((temp, item) => temp + item, 0) } }, actions: { getBooks: function (context) { axios({ url: 'https://www.fastmock.site/mock/37d3b9f13a48d528a9339fbed1b81bd5/book/api/books', method: 'get' }).then(res => { console.log(res); context.commit('updateBook', res.data.data) }) } } }
抽離到allBook.js中后,在index.js中引入,并添加到modules對(duì)象中
import Vue from 'vue' import vuex from 'vuex' import allBook from './modules/allBook.js' Vue.use(vuex) export default new vuex.Store({ modules: { allBook } })
注意:
抽離后.組件中調(diào)用的方式就變了, 還記得我們加了namespaced: true這句話, 加了之后,引用數(shù)據(jù)和方法時(shí)都必須要加上模塊名了
示例: 如何調(diào)用
以及其他三個(gè)調(diào)用方式:
// 例子: 1. // 原先寫(xiě)法: {{$store.getters.sum}} // 15 2. // 抽離后的寫(xiě)法: {{$store.gerters['allBook/sum']}} // 15 // 這里我都列舉一下其他三種的方式 // state: $store.state.模塊名.屬性名 // mutations: $store.commit('模塊名/mutation名') // getters: $store.gerters['模塊名/getter名'] // actions: $store.dispatch('模塊名/action名')
- 補(bǔ)充: 如果要修改state/mutations/getters/actions名字,例如:可以這樣寫(xiě) $store.commit(‘模塊名,{新名字:久名字}’) ,其他的格式都類(lèi)似如此
五、輔助函數(shù)用法(不分modules)
mapState/mapMutations/mapGetters/mapActions
- 作用
用來(lái)優(yōu)化訪問(wèn)的方式, 普通的寫(xiě)法太麻煩了,利用vuex內(nèi)置的方法,可以簡(jiǎn)潔的引用vuex中的數(shù)據(jù)和方法
5.1、mapState函數(shù)()
將state中的變量映射到當(dāng)前組件中使用
使用步驟,代碼如下:
// 當(dāng)前組件中 按需引入mapState // 例如引用vuex中state中的變量 c:30 <template> {{c}} // 30 </template> <script> import { mapState } from 'vuex' export default { computed: { ...mapState(['c']) // 如果需要改名字的話 ...mapState({'新名字':'舊名字'}) } } </script>
computed:{ …mapState() } 這里的…是對(duì)象的展開(kāi)運(yùn)算符,整體來(lái)看是對(duì)象的合并。
5.2、mapMutations
// 在state中定義一個(gè)變量為a:10 // App.vue組件中 <template> <div> {{a}} <button @click="abb">點(diǎn)擊+1</button> </div> </template> <script> import { mapMutations, mapState } from 'vuex' export default { computed: { ...mapState(['a']) }, methods: { ...mapMutations(['add']) }, } </script>
以上列舉了mapState和mapMutations的語(yǔ)法
,其他兩個(gè)(mapGetters和mapActions
)用法和前兩個(gè)都是一樣的
六、輔助函數(shù)用法(分modules)(namespaced:false)
和訪問(wèn)非model用法一樣,不贅述
七、輔助函數(shù)用法(分modules)(namespaced:true)
7.1、mapStates
computed: { ...mapState('模塊名', ['xxx']), ...mapState('模塊名', {'新名字': 'xxx'}) } //或者 computed: { ...mapState(['模塊名/xxx']), ...mapState({'新名字': '模塊名/xxx'}) }
7.2、mapGetters
computed: { ...mapGetters('模塊名', ['xxx']), ...mapGetters('模塊名',{'新名字': 'xxx'}) } //或者 computed: { ...mapGetters(['模塊名/xxx']), ...mapGetters({'新名字': '模塊名/xxx'}) }
7.3、mapMutations
methods: { ...mapMutations('模塊名', ['xxx']), ...mapMutations('模塊名',{'新名字': 'xxx'}) } //或者 methods: { ...mapMutations(['模塊名/xxx']), ...mapMutations({'新名字': '模塊名/xxx'}) }
7.4、mapActions
methods: { ...mapActions('模塊名', ['xxx']), ...mapActions('模塊名',{'新名字': 'xxx'}) } //或者 methods: { ...mapActions(['模塊名/xxx']), ...mapActions({'新名字': '模塊名/xxx'}) }
以上就是VueX學(xué)習(xí)之modules和namespacedVueX詳細(xì)教程的詳細(xì)內(nèi)容,更多關(guān)于VueX modules namespacedVueX的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
vite+vue3代碼風(fēng)格校驗(yàn)及格式化方式
這篇文章主要介紹了vite+vue3代碼風(fēng)格校驗(yàn)及格式化方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03vue使用axios獲取不到響應(yīng)頭Content-Disposition的問(wèn)題及解決
這篇文章主要介紹了vue使用axios獲取不到響應(yīng)頭Content-Disposition的問(wèn)題及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06vue?實(shí)現(xiàn)動(dòng)態(tài)設(shè)置元素的高度
這篇文章主要介紹了在vue中實(shí)現(xiàn)動(dòng)態(tài)設(shè)置元素的高度,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08解決vue更新路由router-view復(fù)用組件內(nèi)容不刷新的問(wèn)題
今天小編就為大家分享一篇解決vue更新路由router-view復(fù)用組件內(nèi)容不刷新的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-11-11vue+elementui 實(shí)現(xiàn)新增和修改共用一個(gè)彈框的完整代碼
Element-Ul是餓了么前端團(tuán)隊(duì)推出的一款基于Vue.js 2.0 的桌面端UI框架,手機(jī)端有對(duì)應(yīng)框架是Mint UI ,今天給大家普及vue+elementui 實(shí)現(xiàn)新增和修改共用一個(gè)彈框的完整代碼,一起看看吧2021-06-06Vue3 構(gòu)建 Web Components使用詳解
這篇文章主要為大家介紹了Vue3 構(gòu)建 Web Components使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09vue+uniapp瀑布流布局多種實(shí)現(xiàn)方式示例代碼
由于使用uniapp開(kāi)發(fā)的微信小程序不需要考慮響應(yīng)式,因此瀑布流的實(shí)現(xiàn)相對(duì)于pc端更為簡(jiǎn)單,下面這篇文章主要給大家介紹了關(guān)于vue+uniapp瀑布流布局多種實(shí)現(xiàn)方式的相關(guān)資料,需要的朋友可以參考下2023-03-03vue watch普通監(jiān)聽(tīng)和深度監(jiān)聽(tīng)實(shí)例詳解(數(shù)組和對(duì)象)
這篇文章主要介紹了vue watch普通監(jiān)聽(tīng)和深度監(jiān)聽(tīng)(數(shù)組和對(duì)象),文中單獨(dú)通過(guò)代碼給大家介紹了vue watch 深度監(jiān)聽(tīng)的方法,感興趣的朋友一起看看吧2018-08-08