vuex在vuecli中的简单使用
2019獨角獸企業重金招聘Python工程師標準>>>
Vuex 是一個專為 Vue.js 應用程序開發的狀態管理模式。它采用集中式存儲管理應用的所有組件的狀態,并以相應的規則保證狀態以一種可預測的方式發生變化。簡單的說,vuex就是將組件中公用的狀態全部抽出來,集中去管理,無論你是獲取狀態還是更改狀態,都通過vuex來進行。
狀態管理模式====》一個簡單的 Vue 計數應用
????new Vue({
????????// state
????????data () { return { count: 0 } },
????????// view
????????template: ` <div>{{ count }}</div> `,
????????// actions
????????methods: { increment () { this.count++ } }
????})
- state,驅動應用的數據源;
- view,以聲明方式將?state?映射到視圖;
- actions,響應在?view?上的用戶輸入導致的狀態變化
????????以下是一個表示“單向數據流”理念的極簡示意:
當我們的應用遇到多個組件共享狀態時,單向數據流的簡潔性很容易被破壞:
- 多個視圖依賴于同一狀態。
- 來自不同視圖的行為需要變更同一狀態。
Vuex 是專門為 Vue.js 設計的狀態管理庫,以利用 Vue.js 的細粒度數據響應機制來進行高效的狀態更新。
由于 store 中的狀態是響應式的,在組件中調用 store 中的狀態簡單到僅需要在計算屬性中返回即可。觸發變化也僅僅是在組件的 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,//通過在根實例中注冊?store?選項,該 store 實例會注入到根組件下的所有子組件中,且子組件能通過?this.$store訪問到
????????components: { App },
????????template: '<App/>'
????})
2、在src目錄下添加vuex目錄,新建store.js文件用來管理狀態? ?
????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獲取這個狀態
????//一般會在組件的計算屬性(computed)獲取state的數據(因為,計算屬性會監控數據變化,一旦發生改變就會響應)
? ? 例如:
? ? ? ?<template>
???????? ????<div><h3>{{mAge}}</h3> </div>
? ? ? ?</template>
????????<script>
????? ? ?export default {
????????????????name : "components3",
???????? ????????computed : {??
????????????????myAge (){ return this.$store.state.age; }
???????? } }
????????</script>
4、修改狀態this.$store.commit( 'showAge', this.msg );
????
轉載于:https://my.oschina.net/huibaifa/blog/1809566
總結
以上是生活随笔為你收集整理的vuex在vuecli中的简单使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2018--Linux命令总结整理复习版
- 下一篇: oracle 的一些基础查询