VueX學習之modules和namespacedVueX詳細教程
一、今天主要解決
什么是vuex?
為什么要用到vuex?
基礎用法?
二、初步認識Vuex
2.1、父子通信,兄弟間通信局限性
父子通信,兄弟間通信我們都知道,但是有復雜的項目,可能會嵌套很多層,這樣一層一層的傳值,很麻煩!不光是對代碼質量造成了影響,也對代碼運行的性能造成了影響,甚至會造成難以排查的bug。
2.2、講個例子
小朋友想要零花錢,會先和媽媽要,媽媽沒有,就去和爸爸要,爸爸把零花錢給了媽媽,媽媽再給了小朋友。這個就很麻煩了,解決辦法,不如直接爸爸把零花錢放在一個指定的位置,誰要,誰就去那個位置拿
2.3、vuex
vuex就是那個指定的地方,官方給起了個很專業(yè)的名字,叫:狀態(tài)管理模式,說白了,就是一個統(tǒng)一存放狀態(tài)的地方,誰用里邊的值都可以取到,無論頁面的層次多深,不用擔心拿不到的問題,這樣解決復雜通信或傳值的問題就很方便了。
三、引入vuex
3.1、安裝
//vue2 npm install --save vuex@3 //vue3 npm install --save vuex
3.2、編寫store的js文件
在src目錄下創(chuàng)建一個文件夾統(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')
四、各個模塊介紹
4.1、 state
export default new vuex.Store({
// 手動定義一些數(shù)據(jù)
state:{
a: 10
}
})
接下來我們在組件中獲取并使用一下這個公共的數(shù)據(jù)
<template>
<div>
{{$store.state.a}} // 頁面中打印出10
</div>
</template>4.2、mutations
主要用于修改state中的數(shù)據(jù)
參數(shù)一: state對應 state對象
參數(shù)二: 形參- 需要傳入的參數(shù),可有可無
語法: mutations:{‘mutations名’:funtion(state,形參) }
例子: 在state中a = 10 , 我們定義一個mutations方法 對state中的a的值進行修改
export default new vuex.Store({
state: {
a: 10
},
mutations: {
state.a += 1 // a+1
},
})
接下來在App.vue中我們寫一個button按鈕用來點擊并調用這個方法 點一次觸發(fā)一次 讓a的值每次加一
<template>
<div>
{{$store.state.a}}
// 點擊一次 就調用一次 進行+1
<button @click="$store.commit('add')">a+1</button>
</div>
</template> - 在模板中: $store.commit(‘mutations名’)
- 在組件中: 要加this調用, this.$store.commit(‘mutations名’)
4.3、getters
- 語法: getters:{ ‘getters名’,function(state,形參)},用法和mutations差不多,
- getters的作用是用于計算數(shù)據(jù)得到計算后的新的數(shù)據(jù) 類似于computed計算數(shù)據(jù)
- 示例: 例如在state中有一個值為b:[1,2,3,4,5],
用getters對這個數(shù)據(jù)進行計算 然后打印到頁面中,具體代碼如下:
getters: {
sum: function (state) {
return state.b.reduce((temp, item) => temp + item, 0)
}
}
在頁面中渲染出來{{$store.getters.sum}} // 15
4.4、actions
語法:
actions:{ ‘action名’,function(context,形參)}
context其實就是對應的state .
- actions用于發(fā)起異步的請求,可以在actions中用axios發(fā)起數(shù)據(jù)請求,獲取數(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中我定義了一個數(shù)組 book:[ ]用來接收獲取到的數(shù)據(jù) , 接收到數(shù)據(jù)res后, 想賦值給book數(shù)組, 但是要記住不能直接進行賦值,必須要在mutations中一個一個賦值的函數(shù), 在actions獲取到數(shù)據(jù).調用mutations中的函數(shù),進行賦值.
接著組件中寫一個button按鈕用來測試 觸發(fā)actions發(fā)起axios請求獲取數(shù)據(jù),并賦值給book數(shù)組
調用actions的方式:
- 模塊中: $store.dispatch(‘actions名’)
- 組件中: this.store.dispatch(‘actions名’)
<template>
<div>
// 點擊 觸發(fā)actions 并發(fā)起axios請求數(shù)據(jù)
<button @click="$store.dispatch('getBooks')">獲取數(shù)據(jù)</button>
{{$store.state.book}} // 打印獲取到的數(shù)據(jù)
</div>
</template>4.5、modules
modules中命名空間默認是namespaced: 為false ,設置true后,在組件中使用拆分到modules的數(shù)據(jù)和方法要加"模塊名"
語法:
modules:{ ‘模塊名’:{state{},mutations:{},getters:{},actions:{} }}
作用
modules用來拆分index.js中的代碼, 減少index.js中代碼的繁多和體積,讓index.js中更簡潔,把相同的需要的數(shù)據(jù)和方法都提取到同一個js中
前提
在store文件中新建modules文件,把state中book數(shù)組和mutations中修改book的方法,以及actions中獲取數(shù)據(jù)的相關代碼剪切到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對象中
import Vue from 'vue'
import vuex from 'vuex'
import allBook from './modules/allBook.js'
Vue.use(vuex)
export default new vuex.Store({
modules: {
allBook
}
})
注意:
抽離后.組件中調用的方式就變了, 還記得我們加了namespaced: true這句話, 加了之后,引用數(shù)據(jù)和方法時都必須要加上模塊名了
示例: 如何調用
以及其他三個調用方式:
// 例子:
1. // 原先寫法: {{$store.getters.sum}} // 15
2. // 抽離后的寫法: {{$store.gerters['allBook/sum']}} // 15
// 這里我都列舉一下其他三種的方式
// state:
$store.state.模塊名.屬性名
// mutations:
$store.commit('模塊名/mutation名')
// getters:
$store.gerters['模塊名/getter名']
// actions:
$store.dispatch('模塊名/action名')- 補充: 如果要修改state/mutations/getters/actions名字,例如:可以這樣寫 $store.commit(‘模塊名,{新名字:久名字}’) ,其他的格式都類似如此
五、輔助函數(shù)用法(不分modules)
mapState/mapMutations/mapGetters/mapActions
- 作用
用來優(yōu)化訪問的方式, 普通的寫法太麻煩了,利用vuex內置的方法,可以簡潔的引用vuex中的數(shù)據(jù)和方法
5.1、mapState函數(shù)()
將state中的變量映射到當前組件中使用
使用步驟,代碼如下:
// 當前組件中 按需引入mapState
// 例如引用vuex中state中的變量 c:30
<template>
{{c}} // 30
</template>
<script>
import { mapState } from 'vuex'
export default {
computed: {
...mapState(['c'])
// 如果需要改名字的話
...mapState({'新名字':'舊名字'})
}
}
</script>computed:{ …mapState() } 這里的…是對象的展開運算符,整體來看是對象的合并。
5.2、mapMutations
// 在state中定義一個變量為a:10
// App.vue組件中
<template>
<div>
{{a}}
<button @click="abb">點擊+1</button>
</div>
</template>
<script>
import { mapMutations, mapState } from 'vuex'
export default {
computed: {
...mapState(['a'])
},
methods: {
...mapMutations(['add'])
},
}
</script>以上列舉了mapState和mapMutations的語法,其他兩個(mapGetters和mapActions)用法和前兩個都是一樣的
六、輔助函數(shù)用法(分modules)(namespaced:false)
和訪問非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學習之modules和namespacedVueX詳細教程的詳細內容,更多關于VueX modules namespacedVueX的資料請關注腳本之家其它相關文章!
相關文章
詳解關于element級聯(lián)選擇器數(shù)據(jù)回顯問題
這篇文章主要介紹了詳解關于element級聯(lián)選擇器數(shù)據(jù)回顯問題,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-02-02
Vue3+Vite如何解決“找不到模塊“@/components/xxx.vue”或其相應的類型聲明ts(2307)”
在Vue項目中使用Vite時,可能因版本差異而需修改tsconfig.app.json而非tsconfig.json以解決編譯錯誤,本文分享個人解決經驗,供參考2024-10-10

