詳解vuex 漸進式教程實例代碼
vuex 漸進式教程,從入門級帶你慢慢深入使用vuex。
Vuex 是什么?
Vuex 是一個專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式。它采用集中式存儲管理應(yīng)用的所有組件的狀態(tài), 并以相應(yīng) 的規(guī)則保證狀態(tài)以一種可預(yù)測的方式發(fā)生變化。
vuex官網(wǎng): vuex.vuejs.org/zh/guide/
安裝
安裝vue-cli:
cnpm install -g vue-cli vue init webpack vuex
安裝vuex
cnpm i vuex --save
1.初級使用方法
// main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import Vuex from 'vuex' // 引入vuex
Vue.config.productionTip = false
Vue.use(Vuex);
let store = new Vuex.Store({ // store 對象
state:{
count:0
}
})
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store, //使用store,這可以把 store 的實例注入所有的子組件
components: { App },
template: '<App/>'
})
此時可以在組件中使用 this.$store.state.count 獲取store中state的值。如:
// 在組件的computed中使用
computed:{
count(){
return this.$store.state.count;
}
}
想想一下當(dāng)項目比較大的時候數(shù)據(jù)繁瑣,如果按照上述方法使用vuex,當(dāng)你打開main.js你看的到場景是比較混亂的,各種數(shù)據(jù)繁雜在一起,不便于日后的維護。請看下一步:
2.中級使用方法: modules 模塊化
state用法
2.1 在main.js中刪除下述這部分代碼
let store = new Vuex.Store({ // store 對象
state:{
count:0
}
})
2.2. 在src目錄下新建store文件夾并在該文件夾下新建index.js文件。 在 store/index.js寫入:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
strict:true, // 開啟嚴(yán)格模式 確保state 中的數(shù)據(jù)只能 mutations 修改
state:{
count:0
}
})
export default store;
對應(yīng)的main.js應(yīng)該寫入:
import store from './store'
寫到這里,我們在組件里就可以獲取到store里的state的值了
2.3 為了方便測試直接在HelloWorld.vue 中使用store
<template>
<div class="hello">
<h2>{{count}}</h2>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
computed:{
count(){
return this.$store.state.count;
}
}
}
</script>
很多時候咱們要對state里的值進行操作,在vuex提供了一個方法mutations
mutations用法(使用mutations可以修改state的值)
在sore\index.js寫入:
//
...
state:{
count:0
},
mutations:{ // 更改數(shù)據(jù)的方法
add(state){
state.count++
},
//提交載荷用法
// add(state,n){
// state.count += n
// },
sub(state){
state.count--
}
}
...
//
組件(HelloWorld.vue)中使用mutations里對應(yīng)的方法:
<template>
<div class="hello">
<button @click="add">+</button>
<h2>{{count}}</h2>
<button @click="sub">-</button>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
computed:{
count(){
return this.$store.state.count;
}
},
methods:{
add(){
this.$store.commit('add');
},
//提交載荷用法
// add(){
// this.$store.commit('add',10);
// },
//對象風(fēng)格的提交方式
// store.commit({
// type: 'add',
// n: 10
// })
sub(){
this.$store.commit('sub');
}
}
}
</script>
此時就可以對count進行修改了。
當(dāng)你想異步操作的時候,由于mutation必須是同步的這一點,此時不能采用mutation對state 進行修改。action派上用場了,action就是一個函數(shù)集合,在里面怎么操作都可以,只要最后觸發(fā)mutation 就可以了。
注解mutation不能異步操作的原因:
mutations: {
add (state) {
api.callAsyncMethod(() => {
state.count++
})
}
}
現(xiàn)在想象,我們正在 debug 一個 app 并且觀察 devtool 中的 mutation 日志。每一條 mutation 被記錄,devtools 都需要捕捉到前一狀態(tài)和后一狀態(tài)的快照。然而,在上面的例子中 mutation 中的異步函數(shù)中的回調(diào)讓這不可能完成:因為當(dāng) mutation 觸發(fā)的時候,回調(diào)函數(shù)還沒有被調(diào)用,devtools 不知道什么時候回調(diào)函數(shù)實際上被調(diào)用——實質(zhì)上任何在回調(diào)函數(shù)中進行的狀態(tài)的改變都是不可追蹤的。
Action 用法
在sore\index.js寫入:
mutations:{ // 更改數(shù)據(jù)的方法
add(state){
state.count++
},
sub(state){
state.count--
}
},
++++
actions:{
add(context){ // context 與 store 實例具有相同方法和屬性(但不是store 實例)
setTimeout(()=>{
context.commit('add');
},1000)
}
}
++++
組件(HelloWorld.vue)中使用getters里對應(yīng)的方法:
<template>
<div class="hello">
<button @click="add">+</button>
++++
<button @click="add_action">action +</button>
++++
<h2>{{count}}</h2>
<button @click="sub">-</button>
<div>
test: {{doneTodos[0].text}} <br>
length: {{doneTodosLength}}
</div>
</div>
</template>
export default {
methods:{
add(){
this.$store.commit('add');
// console.log(this);
},
sub(){
this.$store.commit('sub');
},
++++
add_action(){
this.$store.dispatch('add');
}
++++
}
}
看到這里有沒有想過當(dāng)我們使用state中某一個數(shù)據(jù)時,我們只想用該數(shù)據(jù)中符合條件的數(shù)據(jù)。比如:
state:{
count:0,
todos: [
{ id: 1, text: 'text1--true', done: true },
{ id: 2, text: 'text2--false', done: false }
]
}
此時我們只想獲取state.todos中done為true的數(shù)據(jù)時我們應(yīng)該怎么獲?。?/p>
可能會有以下兩種方案:
1.每個在組件中首先獲取todos,然后使用filter方法過濾;
2.寫一個公共函數(shù)在每個組件中調(diào)用以下;
如果用到todos中done為true的組件很多,這兩種方法都是很不理想的。Vuex為此為我們引入了一個方法Getter。
Getter 用法
官方解釋:Vuex 允許我們在 store 中定義“getter”(可以認(rèn)為是 store 的計算屬性)。就像計算屬性一樣,getter 的返回值會根據(jù)它的依賴被緩存起來,且只有當(dāng)它的依賴值發(fā)生了改變才會被重新計算。
在sore\index.js寫入:
mutations:{ // 更改數(shù)據(jù)的方法
add(state){
state.count++
},
sub(state){
state.count--
}
},
+++
getters:{ // 用法類似組件中的 computed, 可以認(rèn)為是store的計算屬性
doneTodos:state => { // Getter 接受 state 作為其第一個參數(shù):
return state.todos.filter(todo => todo.done) // -> [{ id: 1, text: 'text1--true', done: true }]
},
// Getter 也可以接受其他 getter 作為第二個參數(shù)
doneTodosLength:(state,getters) => {
return getters.doneTodos.length // -> 1
},
+++
}
組件(HelloWorld.vue)中使用getters里對應(yīng)的方法:
<template>
<div class="hello">
<button @click="add">+</button>
<h2>{{count}}</h2>
<button @click="sub">-</button>
+++
<div>
test: {{doneTodos[0].text}} <br>
length: {{doneTodosLength}}
</div>
+++
</div>
</template>
<script>
export default {
//...
computed:{
+++
doneTodos(){
return this.$store.getters.doneTodos // -> [{ id: 1, text: 'text1--true', done: true }]
},
doneTodosLength(){
return this.$store.getters.doneTodosLength // -> 1
}
+++
}
}
</script>
本篇代碼地址: github.com/xioasa/vue-…
總結(jié)
以上所述是小編給大家介紹的vuex 漸進式教程實例代碼,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復(fù)大家的!
相關(guān)文章
基于前端VUE+ElementUI實現(xiàn)table行上移或下移功能(支持跨頁移動)
有時候需要前端實現(xiàn)上移和下移功能,下面這篇文章主要給大家介紹了關(guān)于如何基于前端VUE+ElementUI實現(xiàn)table行上移或下移(支持跨頁移動)的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-07-07
vue3?element-plus實現(xiàn)圖片預(yù)覽功能實例
這篇文章主要給大家介紹了關(guān)于vue3?element-plus實現(xiàn)圖片預(yù)覽功能的相關(guān)資料,在項目中我們經(jīng)常會碰到圖片預(yù)覽的功能需求,文中通過代碼示例介紹的非常詳細(xì),需要的朋友可以參考下2023-09-09
axios全局請求參數(shù)設(shè)置,請求及返回攔截器的方法
下面小編就為大家分享一篇axios全局請求參數(shù)設(shè)置,請求及返回攔截器的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03
Vue.js實現(xiàn)大屏數(shù)字滾動翻轉(zhuǎn)效果
大屏數(shù)字滾動翻轉(zhuǎn)效果來源于最近工作中element后臺管理頁面一張大屏的UI圖,該UI圖上有一個模塊需要有數(shù)字往上翻動的效果。本文通過截圖代碼的形式給大家介紹Vue.js實現(xiàn)大屏數(shù)字滾動翻轉(zhuǎn)效果,感興趣的朋友一起看看吧2019-11-11
淺談vue2 單頁面如何設(shè)置網(wǎng)頁title
這篇文章主要介紹了淺談vue2 單頁面如何設(shè)置網(wǎng)頁title,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-11-11
Vue動態(tài)設(shè)置圖片時src不生效的原因及解決方法
這篇文章主要介紹了Vue動態(tài)設(shè)置圖片時src不生效的原因及解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08

