Vuex入門、同步異步 存取值

目的:

一、瞭解vuex中的各個js文件的用途vue

二、利用vuex存值ios

三、利用vuex取值ajax

四、Vuex的異步同步加載問題vuex

 

1. vuex中各個組件之間傳值

1.父子組件
父組件-->子組件,經過子組件的自定義屬性:props
子組件-->父組件,經過自定義事件:this.$emit('事件名',參數1,參數2,...);npm

2.非父子組件或父子組件

經過數據總數Bus,this.$root.$emit('事件名',參數1,參數2,...)axios

3.非父子組件或父子組件

更好的方式是在vue中使用vuexapp

方法1: 用組件之間通信。這樣寫很麻煩,很容易寫暈。
方法2: 咱們定義全局變量。模塊a的數據賦值給全局變量x。而後模塊b獲取x。這樣咱們就很容易獲取到數據異步

 

2. Vuex

Vuex是Vue.js應用程序的狀態管理模式+庫。它充當應用程序中全部組件的集中存儲,其規則確保狀態只能以可預測的方式進行變動。
async

Vuex分紅五個部分:

State:單一狀態樹
Getters:狀態獲取
Mutations:觸發同步事件
Actions:提交mutation,能夠包含異步操做
Module:將vuex進行分模塊函數

圖解:

 

官方詳解(https://vuex.vuejs.org/

 

3. vuex使用步驟

3.1 安裝

npm install vuex -S

3.2 建立store模塊,分別維護state/actions/mutations/getters

store
index.js
state.js
actions.js
mutations.js
getters.js

 

3.3 在store/index.js文件中新建vuex的store實例,並註冊上面引入的各大模塊

除了index.js之外其餘四個js文件都須要引入下面這個模塊

index.js

import Vue from 'vue' import Vuex from 'vuex' import state from './state' import getters from './getters' import actions from './actions' import mutations from './mutations' Vue.use(Vuex) const store = new Vuex.Store({ state, getters, actions, mutations }) export default store

3.4 在main.js中導入並使用store實例

main.js

import store from './store'

new Vue({ el: '#app', router,  store, //在main.js中導入store實例
 components: { App }, template: '<App/>', data: { //自定義的事件總線對象,用於父子組件的通訊
        Bus: new Vue()  } })

4.vuex的核心概念:store、state、getters、mutations、actions

 

store: 每個Vuex應用的核心就是store(倉庫),store基本上就是一個容器,它包含着你的應用中大部分的狀態 (state)。

 

 

state : 共同維護的一個狀態,state裏面能夠是不少個全局狀態

getters:獲取數據並渲染

actions:數據的異步操做

mutations:處理數據的惟一途徑,state的改變或賦值只能在這裏

圖解:

 

4.1 state(保存數據的容器)

狀態,即要全局讀寫的數據

state.js

export default{
  //定義變量,名字自定義
      htname:'世人皆憐李清照,無人惜我魚玄機',
      hhname:'本是青燈不歸客,卻因濁酒留風塵',
}

讀取:

VuexPage1.vue

<template>
  <div>
    <h2>第一個vuex頁面:</h2>
    <h3>{{ht}}</h3>
  </div>
</template>
<script>
  export default{
    data(){
      return{
      };
    },
    computed: {
      ht() {
        return this.$store.state.htname;   //不推薦這種方式
      }
    },
  }
</script>

效果:

 

還有一種方式獲取值

VuexPage2.vue

<template>
  <div>
    <h2>第二個vuex頁面:</h2>
    <h3>{{ht}}</h3>
  </div>
</template>
<script>
  export default{
    data(){
      return{
          ht:''
      };
    },
    //使用鉤子函數
    created(){
       this.ht=this.$store.state.hhname;
    },
  }
</script>

效果:

 

4.2 getters(getXxx)

獲取數據並渲染

注1:getters將state中定義的值暴露在this.$store.getters對象中,咱們能夠經過以下代碼訪問
this.$store.getters.name

注2:state狀態存儲是響應式的,從store實例中讀取狀態最簡單的方法就是在計算屬性中返回某個狀態

4.3 mutations(setXxx)

處理數據的惟一途徑,state的改變或賦值只能在這裏

注1:mutations中方法的調用方式
不能直接調用this.$store.mutations.setResturantName('KFC'),必須使用以下方式調用:
this.$store.commit(type,payload);

// 一、把載荷和type分開提交
store.commit('setResturantName',{
resturantName:'KFC'
})

// 二、載荷和type寫到一塊兒

store.commit({

type: 'setResturantName',resturantName: 'KFC'})


注2:必定要記住,Mutation 必須是同步函數。爲何呢?異步方法,咱們不知道何時狀態會發生改變,因此也就沒法追蹤了
若是咱們須要異步操做,Mutations就不能知足咱們需求了,這時候咱們就須要Actions了

4.4 actions
數據的異步(async)操做

 sethtnameAsync: (context, payload) => { console.log('啦啦啦'); setTimeout(() => { console.log('哈哈哈'); context.commit('sethtname', payload); }, 3000); console.log('略略略'); },

vuex綜合完整案例

定義變量 state.js

export default{
  //定義變量,名字自定義
      htname:'世人皆憐李清照,無人惜我魚玄機', //後面基本上用的是這個變量
      hhname:'本是青燈不歸客,卻因濁酒留風塵',
}

顯示頁面VuePage1.vue

<template>
  <div>
    <h2>第一個vuex頁面:</h2>
    <h3>{{ht}}</h3>
    <button @click="hscht">換詩詞</button>
    <button @click="hschtAsync">一個月後換詩詞</button>
    <button @click="doAjax">測試vuex中使用ajax</button>
  </div>
</template>
<script> export default{ data(){ return{ }; }, methods: { hscht() { this.$store.commit('sethtname',{ htname:'一身詩意千尋普,萬古人間四月天', }); }, hschtAsync() { this.$store.dispatch('sethtnameAsync',{ htname:'世事一場大夢,人生幾度秋涼', }); }, doAjax(){ this.$store.dispatch('doAjax',{ _this:this, }); } }, computed: { ht() { // return this.$store.state.htname; //不推薦這種方式
        return this.$store.getters.gethtname; } }, } </script>
<style>
</style>

getters.js 獲取數據而且渲染

export default{
   gethtname: (state) => {
         return state.htname;
     }
}

效果:

mutations.js

export default {
  sethtname: (state, payload) => {
    state.htname = payload.htname;
  },
}

效果就是點擊換詩詞就會換成別的詩詞

==》點擊換詩詞

如今咱們來用Action來代替mutations

export default {
  sethtnameAsync: (context, payload) => {
    console.log('啦啦啦');
    setTimeout(() => {
      console.log('哈哈哈');
      context.commit('sethtname', payload);
    }, 3000);
    console.log('略略略');
  },
  doAjax:(context, payload) => {
    //vuex是不能被vue實例的
    let _this =payload._this;
    let url = this.axios.urls.SYSTEM_USER_DOLOGIN;
    // let url = 'http://localhost:8080/T216_SSH/vue/userAction_login.action';
     console.log(url);
    _this.axios.post(url,{}).then((response) => {
        console.log('doAjax............');
        console.log(response);
      }).catch((response)=>{
        console.log(response);
      });
    },
  }

效果是:我給它設定了三秒鐘,因此三秒鐘後它自動換詩詞(爲了展現效果就輸出在控制檯看是否成功),而且參加了異步玩法

 

 

 

 

謝謝觀看!

相關文章
相關標籤/搜索