天天看點

簡單的vuex 的使用

1、 npm install vuex 

2、 在src 下 建立檔案夾 store (為什麼是這個單詞,vuex 是用來狀态管理的,用儲存一些元件的狀态,取存貯,倉庫之意),store 檔案下 建立檔案 index.js  (為什麼是index.js? 在導入的時候,會第一選擇這個叫index的檔案) 

3、 index.js import 導入 vue 和vuex (import 是es6 的文法, es5 是 require), 代碼如下:

  這裡的demo 是一個 改變 app 的模式 的一個appellation ,選擇是 夜間模式還是白天模式

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    night: true,
    text: '白天',
    className: 'morning'
  },
  mutations: {
    increment (state) {
      state.night = !state.night;
      state.text = state.night === true ? '晚上' : '白天';
      state.className = state.night === true ? 'night' : 'morning';
    }
  }
})      

4、 main.js import 這個index.js 代碼如下:

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store' // 會找index.js 
 
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store, // 注入根元件,其他子元件 都可以引用
  template: '<App/>',
  components: { App }
})      

5、使用vuex 的狀态

元件1:

dom :

<div class="header" :class="model">

js

computed: {
    model() {
      return this.$store.state.className // 是ninght 還是  morning
    }
  },      

注意:

:class="model" 這個class 可以綁定一個方法傳參數,可以直接用 js 表達式,可以綁定一個計算屬性

元件2:

dom:

<div class='modal' @click="changeModel">
  <div class="avatar">
  <img src="../../assets/img/logo.png" width="18" height="18">
 </div>
 <div class="name">
   {{currentModel}}
 </div> 
  <!-- vuex  相當于全局注入 vuex  然後取這裡面的值 -->
</div>      

js:

computed: {
    currentModel () {
      return this.$store.state.text
    }
  },
  methods: {
    changeModel () {
      // document.body.className='night'
      this.$store.commit('increment')
    }
  }      

j s 中的 currentModel 和 dom 中的 {{ currentModel }} 是一個,和 :class 可以跟表達方法一樣 ,可以跟變量 ,表達方法 ,表達式 ( 這裡靈活的模版方法,回頭檢視下源碼,然後補充這的說明, vue模版為何如此強大!)

點選事件,觸發方法 changeModel ,changeModel 觸發 mutation 的方法,顯示改變 值 ,這個是固定的文法, this.$store.commit('increment');

increment 可以在定義的時候,設定參數,傳參數, this.$store.commit('increment', 'argumnet') , 在 mutation 裡面  increment (state , arg) { .. = arg; ....};

截圖如下:

預設方式:

簡單的vuex 的使用

如上圖顯示。預設的是,白天的模式,className 是 morning; 

  點選事件觸發模式;

簡單的vuex 的使用

再次點選的時候,可以在改回來,這個竅門,就是 index.js 裡面,increment 對 night 的變量 取 對 的一個邏輯方法。跟jq 裡面的 toggle,類似

簡單的vuex 的使用

結束語:

簡單的vuex 的案例 ,做個筆記,不對之處,歡迎大家批評指出; 這裡是一個關于vuex 源碼分析的文章,很長,有興趣的同學可以研究研究

下面講一個稍微進階點的例子: 引入vuex 裡面的  

mapState, mapGetters, mapActions, mapMutations

http://www.jqhtml.com/9032.html
下一篇: css loading

繼續閱讀