首頁 > 軟體

vuex的幾個屬性及其使用傳參方式

2023-01-20 14:00:30

vuex概念

1.1、元件之間共用資料的方式

父 向 子 傳值:v-bind屬性綁值

子 向 父 傳值:v-on事件繫結

兄弟元件之間共用資料:EventBus

  • $on 接收資料的那個元件
  • $emit 傳送資料的那個元件

1.2、Vuex是什麼

Vuex是實現元件全域性狀態(資料)管理的一種機制,可以方便的實現元件之間資料的共用。

1.3、使用Vuex同意管理狀態的好處

能夠在vuex中集中管理共用的資料,易於開發和後期維護

能夠高效地實現元件之間的資料共用,提高開發效率

儲存在vuex中的資料都是響應式的,能夠實時保持資料與頁面的同步。

1.4、什麼樣的資料適合儲存到Vuex中

一般情況下,只有元件之間共用的資料,才有必要儲存到vuex中;對於元件中的私有資料,依然儲存在元件自身的data中即可。

vuex的基本使用

1、安裝vuex依賴包

npm i vuex --save

2、匯入vuex包

import Vuex from 'vuex'
Vue.use(Vuex)

3、建立stroe物件

const store = new Vuex.Store({
    //state中存放的就是全域性共用的資料
	state:{count:0}
})

4、將store物件掛載到vue範例中

new Vue({
	el:'#app',
	render:h => h(app),
	router,
	//將建立的共用資料物件,掛載到vue範例中
	//所有的元件,就可以直接從stroe中獲取全域性的資料了
	store
})

vuex的核心概念

1、vuex中的主要核心概念如下

State

State提供唯一的公共資料來源, 所有共用的資料都要統放到Store的State中進行儲存。

export default new Vuex.Store({
  state: {
    count: 0
  },
})

元件存取State中資料的**第一種方式:**Addition.vue

this.$store.state.全域性資料名稱

<h3>當前最新的count值為:{{$store.state.count}}</h3>

元件存取State中資料的第二種方式: Subtraction.vue

// 1. 從 vuex 中按需匯入 mapState 函數
import { mapState } from 'vuex'

通過剛才匯入的 mapState 函數,將當前元件需要的全域性資料,對映為當前元件的 computed 計算屬性:

<h3>當前最新的count值為:{{count}}</h3>


// 2. 將全域性資料,對映為當前元件的計算屬性
computed: {
 ...mapState(['count'])
}

Mutation

Mutation 用於變更 Store中 的資料。

只能通過 mutation 變更 Store 資料,不可以直接操作 Store 中的資料。

② 通過這種方式雖然操作起來稍微繁瑣一些,但是可以集中監控所有資料的變化。

第一種方式

(1)

// 定義 Mutation    store.js
 const store = new Vuex.Store({
 	state: {
 		count: 0
 	},
	mutations: {
 		add(state) {
 		// 不要在 mutations 函數中,執行非同步操作
      	// setTimeout(() => {
      	//   state.count++
      	// }, 1000)
	 	// 變更狀態
	 	state.count++
	 	}
 	}
 })

在元件中存取Mutation Addition.vue

 <button @click="btnHandler1">+1</button>

methods:{
	//觸發mutation
    btnHandler1() {
	  //觸發 mutations 的第一種方式
      this.$store.commit('add')
    },
}

(2)可以在觸發 mutations 時傳遞引數:

 // 定義Mutation
 const store = new Vuex.Store({
 	state: {
 	count: 0
 	},
 	mutations: {
		 addN(state, step) {
 			// 變更狀態
			 state.count += step
		 }
 	}
 })

在元件中存取Mutation Addition.vue

 <button @click="btnHandler2">+N</button>
 
  methods: {
    btnHandler2() {
      // commit 的作用,就是呼叫 某個 mutation 函數  攜帶引數
      this.$store.commit('addN', 3)
    },
  }

第二種方式

this.$store.commit() 是觸發 mutations 的第一種方式,觸發 mutations 的第二種方式:

// 1. 從 vuex 中按需匯入 mapMutations 函數
import { mapMutations } from 'vuex'

通過剛才匯入的 mapMutations 函數,將需要的 mutations 函數,對映為當前元件的 methods 方法:

// 2. 將指定的 mutations 函數,對映為當前元件的 methods 函數
methods: {
 ...mapMutations(['add', 'addN'])
}

完整程式碼:

//store.js
export default new Vuex.Store({
  state: {
    count: 0
  },
  // 只有 mutations 中定義的函數,才有權利修改 state 中的資料
  mutations: {
    //減減
    sub(state) {
      state.count--
    },
      //攜帶引數
    subN(state, step) {
      state.count -= step
    }
  },
})

在元件中Subtraction.vue

<h3>當前最新的count值為:{{count}}</h3>
<button @click="btnHandler1">-1</button>
//<button @click="btnHandler2">-1</button>
<button @click="subN(3)">-N</button>            -----攜帶引數

import { mapState, mapMutations} from 'vuex'


 computed: {
    ...mapState(['count']),
  },
  methods: {
    ...mapMutations(['sub', 'subN']),
    btnHandler1() {
      this.sub()
    },
 	//btnHandler2() {
      //this.subN(3)
    //},
  }

Action

(1)Action 用於處理非同步任務。

如果通過非同步操作變更資料,**必須通過 Action,而不能使用 Mutation,**但是在 Action 中還是要通過觸發Mutation 的方式間接變更資料。

第一種方式

(1)處理非同步任務

// 定義 Action
 const store = new Vuex.Store({
	 // ...省略其他程式碼
	 mutations: {
 		add(state) {
 			state.count++
 		}
 	},
 	actions: {
 		addAsync(context) {
 			setTimeout(() => {
 				context.commit('add')
 			}, 1000)
 		} 
 	}
 })

在元件中Addition.vue

<button @click="btnHandler3">+1 Async</button>

// 非同步地讓 count 自增 +1
btnHandler3() {
    // 這裡的 dispatch 函數,專門用來觸發 action
    this.$store.dispatch('addAsync')
},

(2)攜帶引數

觸發 actions 非同步任務時攜帶引數:

// 定義 Action
 const store = new Vuex.Store({
 	// ...省略其他程式碼
 	mutations: {
 		addN(state, step) {        -------------攜帶引數
			 state.count += step
 		}
 	},
 	actions: {
 		addNAsync(context, step) {   -------------攜帶引數
 			setTimeout(() => {
 				context.commit('addN', step)
 			}, 1000)
 		} 
 	}
 })

在元件中

<button @click="btnHandler4">+N Async</button>

btnHandler4() {
      this.$store.dispatch('addNAsync', 5)
}

第二種方式

this.$store.dispatch() 是觸發 actions 的第一種方式,觸發 actions 的第二種方式:

// 1. 從 vuex 中按需匯入 mapActions 函數
import { mapActions } from 'vuex'

通過剛才匯入的 mapActions 函數,將需要的 actions 函數,對映為當前元件的 methods 方法:

// 2. 將指定的 actions 函數,對映為當前元件的 methods 函數
methods: {
 ...mapActions(['addASync', 'addNASync'])
}

完整程式碼

export default new Vuex.Store({
  state: {
    count: 0
  },
  // 只有 mutations 中定義的函數,才有權利修改 state 中的資料
  mutations: {
    //減減
    sub(state) {
      state.count--
    },
    subN(state, step) {
      state.count -= step
    }
  },
  //actions可以處理非同步任務
  actions: {
    subAsync(context) {
      setTimeout(() => {
        // 在 actions 中,不能直接修改 state 中的資料;
        // 必須通過 context.commit() 觸發某個 mutation 才行
        context.commit('sub')
      }, 1000)
    },
    subNAsync(context, step) {
      setTimeout(() => {
        context.commit('subN', step)
      }, 1000)
    }
  },
})

元件Subtraction.vue

<h3>當前最新的count值為:{{count}}
<button @click="subAsync">-1 Async</button>
<button @click="subNAsync(5)">-N Async</button>
 
import { mapState, mapMutations, mapActions } from 'vuex'

methods: {
    ...mapActions(['subAsync', 'subNAsync']),
}

**Getter **

不會修改state裡面的資料

Getter 用於對 Store 中的資料進行加工處理形成新的資料。

① Getter 可以對 Store 中已有的資料加工處理之後形成新的資料,類似 Vue 的計算屬性。

② Store 中資料發生變化,Getter 的資料也會跟著變化。

// 定義 Getter
 const store = new Vuex.Store({
	state: {
 		count: 0
 	},
 	getters: {
 		showNum: state => {
 			return '當前最新的數量是【'+ state.count +'】'
 		}
 	}
 })

使用getters的第一種方式

this.$store.getters.名稱

使用getters的第一種方式

{{showNum}}

import { mapGetters } from 'vuex'
computed: {
 ...mapGetters(['showNum'])
}
  • 只有 mutations 中定義的函數,才有權利修改 state 中的資料
  • actions 中,不能直接修改 state 中的資料必須通過 context.commit() 觸發某個 mutation 才行
  • commit 的作用,就是呼叫 某個 mutation 函數
  • dispatch 函數,專門用來觸發 action

到此這篇關於vuex的幾個屬性及其使用傳參的文章就介紹到這了,更多相關vuex屬性使用傳參內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com