Vuex 使用及簡單實例(計數(shù)器)
前一段時間因為需要使用vue,特地去學習了一下。但是時間匆忙vuex沒有接觸到,今天閑暇時看了解了一下vuex,并做了一個小demo,用于記錄vuex的簡單使用過程。
什么是Vuex?
vuex是專門為vue.js應用程序開發(fā)的一種狀態(tài)管理模式,當多個視圖依賴于同一個狀態(tài)或是多個視圖均可更改某個狀態(tài)時,將共享狀態(tài)提取出來,全局管理。
引入Vuex(前提是已經(jīng)用Vue腳手架工具構建好項目)
1、利用npm包管理工具,進行安裝 vuex。在控制命令行中輸入下邊的命令就可以了。
npm install vuex --save
要注意的是這里一定要加上 –save,因為你這個包我們在生產(chǎn)環(huán)境中是要使用的。
2、新建一個store文件夾(這個不是必須的),并在文件夾下新建store.js文件,文件中引入我們的vue和vuex。
import Vue from 'vue'; import Vuex from 'vuex';
3、使用我們vuex,引入之后用Vue.use進行引用。
Vue.use(Vuex);
通過這三步的操作,vuex就算引用成功了,接下來我們就可以盡情的玩耍了。
4、在main.js 中引入新建的vuex文件
import storeConfig from './vuex/store'
5、再然后 , 在實例化 Vue對象時加入 store 對象 :
new Vue({ el: '#app', router, store,//使用store template: '<App/>', components: { App } })
下面是一個計數(shù)器的例子
在src目錄下創(chuàng)建一個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) }
當然了,載荷也可以是一個對象,這樣可以提交多個參數(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="請輸入內容" 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>
到這里這個demo就結束了,
感覺整個個過程就是一個傳輸數(shù)據(jù)的過程,有點類似全局變量,但是vuex是響應式的。
這里當然并沒有完全發(fā)揮出全部的vuex,
vuex還在學習中,寫這篇文章主要是記錄其簡單的使用過程。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Vue3封裝自動滾動列表指令(含網(wǎng)頁縮放滾動問題)
本文主要介紹了Vue3封裝自動滾動列表指令(含網(wǎng)頁縮放滾動問題),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-05-05vue單文件組件lint error自動fix與styleLint報錯自動fix詳解
這篇文章主要給大家介紹了關于vue單文件組件lint error自動fix與styleLint報錯自動fix的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-01-01axios上傳文件錯誤:Current?request?is?not?a?multipart?request
最近工作中使用vue上傳文件的時候遇到了個問題,下面這篇文章主要給大家介紹了關于axios上傳文件錯誤:Current?request?is?not?a?multipart?request解決的相關資料,需要的朋友可以參考下2023-01-01