前一段時(shí)間因?yàn)樾枰褂胿ue,特地去學(xué)習(xí)了一下。但是時(shí)間匆忙vuex沒有接觸到,今天閑暇時(shí)看了解了一下vuex,并做了一個(gè)小demo,用于記錄vuex的簡(jiǎn)單使用過程。
什么是Vuex?
vuex是專門為vue.js應(yīng)用程序開發(fā)的一種狀態(tài)管理模式,當(dāng)多個(gè)視圖依賴于同一個(gè)狀態(tài)或是多個(gè)視圖均可更改某個(gè)狀態(tài)時(shí),將共享狀態(tài)提取出來,全局管理。
引入Vuex(前提是已經(jīng)用Vue腳手架工具構(gòu)建好項(xiàng)目)
1、利用npm包管理工具,進(jìn)行安裝 vuex。在控制命令行中輸入下邊的命令就可以了。
npm install vuex --save
要注意的是這里一定要加上 –save,因?yàn)槟氵@個(gè)包我們?cè)谏a(chǎn)環(huán)境中是要使用的。
2、新建一個(gè)store文件夾(這個(gè)不是必須的),并在文件夾下新建store.js文件,文件中引入我們的vue和vuex。
import Vue from 'vue'; import Vuex from 'vuex';
3、使用我們vuex,引入之后用Vue.use進(jìn)行引用。
Vue.use(Vuex);
通過這三步的操作,vuex就算引用成功了,接下來我們就可以盡情的玩耍了。
4、在main.js 中引入新建的vuex文件
import storeConfig from './vuex/store'
5、再然后 , 在實(shí)例化 Vue對(duì)象時(shí)加入 store 對(duì)象 :
new Vue({ el: '#app', router, store,//使用store template: '<App/>', components: { App } })
下面是一個(gè)計(jì)數(shù)器的例子
在src目錄下創(chuàng)建一個(gè)store文件夾。
src/store.js
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state: { count: 0, show: '' }, getters: { counts: (state) => { return state.count } }, mutations: { increment: (state) => { state.count++ }, decrement: (state) => { state.count-- }, changTxt: (state, v) => { state.show = v } } }) export default store
state就是我們的需要的狀態(tài),狀態(tài)的改變只能通過提交mutations,例如:
handleIncrement () { this.$store.commit('increment') }
帶有載荷的提交方式:
changObj () { this.$store.commit('changTxt', this.obj) }
當(dāng)然了,載荷也可以是一個(gè)對(duì)象,這樣可以提交多個(gè)參數(shù)。
changObj () { this.$store.commit('changTxt', { key:'' }) }
在main.js中引入store.js
import store from './store/store' export default new Vue({ el: '#app', router, store, components: { App }, template: '<App/>' })
在組件中使用
在組建可以通過$store.state.count
獲得狀態(tài)
更改狀態(tài)只能以提交mutation的方式。
<template> <div class="store"> <p> {{$store.state.count}} </p> <el-button @click="handleIncrement"><strong>+</strong></el-button> <el-button @click="handleDecrement"><strong>-</strong></el-button> <hr> <h3>{{$store.state.show}}</h3> <el-input placeholder="請(qǐng)輸入內(nèi)容" v-model="obj" @change="changObj" clearable> </el-input> </div> </template> <script> export default { data () { return { obj: '' } }, methods: { handleIncrement () { this.$store.commit('increment') }, handleDecrement () { this.$store.commit('decrement') }, changObj () { this.$store.commit('changTxt', this.obj) } } } </script>
到這里這個(gè)demo就結(jié)束了,
感覺整個(gè)個(gè)過程就是一個(gè)傳輸數(shù)據(jù)的過程,有點(diǎn)類似全局變量,但是vuex是響應(yīng)式的。
這里當(dāng)然并沒有完全發(fā)揮出全部的vuex,
vuex還在學(xué)習(xí)中,寫這篇文章主要是記錄其簡(jiǎn)單的使用過程。
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com