vuex 漸進(jìn)式教程,從入門級(jí)帶你慢慢深入使用vuex。
Vuex 是什么?
Vuex 是一個(gè)專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式。它采用集中式存儲(chǔ)管理應(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.初級(jí)使用方法
// main.jsimport Vue from 'vue'import App from './App'import router from './router'import Vuex from 'vuex' // 引入vuexVue.config.productionTip = falseVue.use(Vuex);let store = new Vuex.Store({ // store 對(duì)象 state:{ count:0 }})/* eslint-disable no-new */new Vue({ el: '#app', router, store, //使用store,這可以把 store 的實(shí)例注入所有的子組件 components: { App }, template: '<App/>'})此時(shí)可以在組件中使用 this.$store.state.count 獲取store中state的值。如:
// 在組件的computed中使用 computed:{ count(){ return this.$store.state.count; } }想想一下當(dāng)項(xiàng)目比較大的時(shí)候數(shù)據(jù)繁瑣,如果按照上述方法使用vuex,當(dāng)你打開main.js你看的到場景是比較混亂的,各種數(shù)據(jù)繁雜在一起,不便于日后的維護(hù)。請(qǐng)看下一步:
2.中級(jí)使用方法: modules 模塊化
state用法
2.1 在main.js中刪除下述這部分代碼
let store = new Vuex.Store({ // store 對(duì)象 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;對(duì)應(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>很多時(shí)候咱們要對(duì)state里的值進(jìn)行操作,在vuex提供了一個(gè)方法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-- } }...//
新聞熱點(diǎn)
疑難解答
圖片精選