vuex在vuecli中的简单使用
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
Vuex 是一個(gè)專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式。它采用集中式存儲管理應(yīng)用的所有組件的狀態(tài),并以相應(yīng)的規(guī)則保證狀態(tài)以一種可預(yù)測的方式發(fā)生變化。簡單的說,vuex就是將組件中公用的狀態(tài)全部抽出來,集中去管理,無論你是獲取狀態(tài)還是更改狀態(tài),都通過vuex來進(jìn)行。
狀態(tài)管理模式====》一個(gè)簡單的 Vue 計(jì)數(shù)應(yīng)用
????new Vue({
????????// state
????????data () { return { count: 0 } },
????????// view
????????template: ` <div>{{ count }}</div> `,
????????// actions
????????methods: { increment () { this.count++ } }
????})
- state,驅(qū)動(dòng)應(yīng)用的數(shù)據(jù)源;
- view,以聲明方式將?state?映射到視圖;
- actions,響應(yīng)在?view?上的用戶輸入導(dǎo)致的狀態(tài)變化
????????以下是一個(gè)表示“單向數(shù)據(jù)流”理念的極簡示意:
當(dāng)我們的應(yīng)用遇到多個(gè)組件共享狀態(tài)時(shí),單向數(shù)據(jù)流的簡潔性很容易被破壞:
- 多個(gè)視圖依賴于同一狀態(tài)。
- 來自不同視圖的行為需要變更同一狀態(tài)。
Vuex 是專門為 Vue.js 設(shè)計(jì)的狀態(tài)管理庫,以利用 Vue.js 的細(xì)粒度數(shù)據(jù)響應(yīng)機(jī)制來進(jìn)行高效的狀態(tài)更新。
由于 store 中的狀態(tài)是響應(yīng)式的,在組件中調(diào)用 store 中的狀態(tài)簡單到僅需要在計(jì)算屬性中返回即可。觸發(fā)變化也僅僅是在組件的 methods 中提交 mutation。
1、安裝和注冊vuex
????npm install vuex --save-dev
? ? 安裝完成之后在main.js中引用
????import Vuex from 'vuex'
????import store from './vuex/store'
? ?
????Vue.use(Vuex)
????Vue.config.productionTip = false;
????/* eslint-disable no-new */
????new Vue({
????????el: '#app',
????????router,
????????store,//通過在根實(shí)例中注冊?store?選項(xiàng),該 store 實(shí)例會(huì)注入到根組件下的所有子組件中,且子組件能通過?this.$store訪問到
????????components: { App },
????????template: '<App/>'
????})
2、在src目錄下添加vuex目錄,新建store.js文件用來管理狀態(tài)? ?
????import Vue from 'vue'
????import Vuex from 'vuex'
????Vue.use(Vuex)
????const store = new Vuex.Store({
????????state:{
????????????age:19
????????},
????????mutations:{
????????????showAge(state,msg){
????????????????????state.age=msg
????????????}
????}
????})
export default store
3、在組件中用this.$store.state.age獲取這個(gè)狀態(tài)
????//一般會(huì)在組件的計(jì)算屬性(computed)獲取state的數(shù)據(jù)(因?yàn)?#xff0c;計(jì)算屬性會(huì)監(jiān)控?cái)?shù)據(jù)變化,一旦發(fā)生改變就會(huì)響應(yīng))
? ? 例如:
? ? ? ?<template>
???????? ????<div><h3>{{mAge}}</h3> </div>
? ? ? ?</template>
????????<script>
????? ? ?export default {
????????????????name : "components3",
???????? ????????computed : {??
????????????????myAge (){ return this.$store.state.age; }
???????? } }
????????</script>
4、修改狀態(tài)this.$store.commit( 'showAge', this.msg );
????
轉(zhuǎn)載于:https://my.oschina.net/huibaifa/blog/1809566
總結(jié)
以上是生活随笔為你收集整理的vuex在vuecli中的简单使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2018--Linux命令总结整理复习版
- 下一篇: html5倒计时秒杀怎么做,vue 设