目錄
一、理解Vuex
1.Vuex是什么
2.什么時候使用Vuex
3.Vuex作業原理圖
二、搭建vuex環境
1.創建檔案:src/store/index.js
2.在main.js中創建vm時傳入store配置項
三、基本使用
1.初始化資料、配置actions、配置mutations、操作檔案store.js
2.組件中讀取vuex中的資料
3.組件中修改vuex中的資料
一、理解Vuex
1.Vuex是什么
概念:專門在Vue中實作集中式狀態(資料)管理的一個 Vue 插件,對 Vue 應用中多個組件的共享狀態進行集中式的管理(讀/寫),也是一種組件間通信的方式,且適用于任意組件間通信,
下面兩張圖是多組件共享資料分別用全域事件總線實作和用vuex實作的比較:


2.什么時候使用Vuex
1.多個組件依賴于同一種狀態
2.來自不同組件的行為需要變更同一狀態
3.Vuex作業原理圖

二、搭建vuex環境
1.創建檔案:src/store/index.js
//引入Vue核心庫
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//應用Vue插件
Vue.use(Vuex)
//準備actions——用于回應組件中的動作
const actions = {}
//準備mutations——用于操作資料(state)
const mutations = {}
//準備state——用于存盤資料
const state = {}
//創建并暴露store
export default new Vuex.Store({
actions,
mutations,
state,
})
2.在main.js中創建vm時傳入store配置項
......
//引入store
import store from './store'
......
//創建vm
new Vue({
el:'#app',
render:h => h(App),
store
})
三、基本使用
1.初始化資料、配置actions、配置mutations、操作檔案store.js
//引入Vue核心庫
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//參考Vuex
Vue.use(Vuex)
//準備actions——用于回應組件中的動作
const actions = {
//回應組件中加的動作
jia(context, value) {
context.commit('JIA', value)
}
}
//準備mutations——用于操作資料(state)
const mutations = {
//執行加
JIA(state, value) {
//console.log('mutations中的加被呼叫了');
state.sum += value
}
}
//準備state——用于存盤資料
//初始化資料
const state = {
sum: 0,
}
//創建并暴露store
export default new Vuex.Store({
actions,
mutations,
state,
})
2.組件中讀取vuex中的資料
$store.state.sum
3.組件中修改vuex中的資料
$store.dispatch('actions中的方法名',資料) 或 $store.commit('motations中的方法名',資料)
備注:若沒有網路請求或其他業務邏輯,組件中也可以越過actions,即不寫dispatch,直接撰寫commit
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/401656.html
標籤:其他
