1. 程式人生 > >Vuex以及axios的使用

Vuex以及axios的使用

Vuex簡介

vuex是一個專門為Vue.js設計的集中式狀態管理架構。

狀態? 我們把它理解為在data中需要共享給其他元件使用的部分。

Vuex和單純的全域性物件有以下不同:

1、Vuex 的狀態儲存是響應式的。當vue元件從store中讀取狀態的時候,

  若store中的狀態發生變化,那麼相應的元件也會相應的得到高效更新。

2、你不能直接改變store中的狀態。改變store中的狀態的唯一途徑就是顯示的

  提交(commit)mutation。這樣使得我們可以方便的跟蹤每一個狀態的變化,

  從而讓我們能夠實現一些工具來幫助我們更好的瞭解我們的應用

 

安裝使用vuex

  --  npm install vuex

// main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import vuex from 'vuex'

Vue.use(vuex)

Vue.config.productionTip = false

const store = new vuex.Store({
    state: {
      show: false,
    }
});

new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
});

使用:
/ 為了方便維護,我們通常把在src下面新建一個store資料夾,
// 然後在裡面新建一個index.js
import Vue from 'vue'
import Vue_x from "vuex"

Vue.use(Vue_x);

export default  new Vue_x.Store({
   state: {
      show: false,
    },
});
// 那麼main.js要改成
import Vue from 'vue'
import App from './App'
import router from './router'
import store from "./store"

Vue.config.productionTip = false;

new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
});
 

State

 

簡而言之~~state是儲存我們data中需要共享的資料。

 

由於Vuex的儲存是響應式的,從store例項中讀取狀態的最簡單的方式就是在計算屬性中返回某個狀態。

 

this.$store.state.count

元件中獲取vuex中狀態:

 

/ 建立一個元件
const Counter = {
  template: `<div>{{ count }}</div>`,
  computed: {
    count(){
      return this.$store.state.count
    }
  }
};

Getter

有時候我們需要從store中的state中派生出一些狀態,例如對資料進行簡單的計算。

並且很多元件都需要用到此方法,我們要麼複製這個函式,要麼抽取到一個公共函式,多處匯入。

我們vuex提供了更加方便的方法,getter ,它就像計算屬性一樣,getter的返回值會根據它的依賴被

快取起來,只有它的依賴發生改變時,才會重新計算。

Getter會接收state作為其第一個引數

Getter使用:

import Vue from 'vue'
import Vue_x from "vuex"

Vue.use(Vue_x);

export default  new Vue_x.Store({
   state: {
     count: 20,
   },
  // 通過 this.$store.getters.my_func
  getters: {
    my_func: function (state) {
      return state.count * 2
    }
  },

});
Getter也可以接收getters為第二個引數:
 
import Vue from 'vue'
import Vue_x from "vuex"

Vue.use(Vue_x);

export default  new Vue_x.Store({
   state: {
     count: 20,
   },
  // 通過 this.$store.getters.my_func
  getters: {
    my_func: function (state) {
      return state.count * 2
    },
    // 通過 this.$store.getters.my_func_count
    my_func_count: function (state, getters) {
      return getters.my_func.length
    }
  },

});

 

Mutation需要遵守Vue的響應規則

 

既然vuex中的store中的狀態是響應式的,那麼當我們狀態變更時,監視狀態的vue元件也會更新。

 

這就意味著vuex中的mutation也需要與使用vue一樣遵守一些注意事項:

 

  -- 1,最好提前在你的store中初始化好所有的所需要的屬性

 

  -- 2,當物件需要新增屬性時,你應該使用

 

      --  Vue.set(obj, 'newProp', 123)

 

      --  以新物件代替老物件  state.obj = { ...state.obj, newProp: 123}

 

axios的簡單使用

 

基於Promise的HTTP請求客戶端,可以同時在瀏覽器和node.js使用。

 

使用npm安裝axios

 

  -- npm install axios -D

 

基本的配置

// main.js
import axios from "axios"

Vue.prototype.$axios = axios

// 元件中
methods: {
     init () {
        this.$axios({
             method: "get",
             url: "/user"
        })
    },
};
 

基本的使用

test(){
          this.$axios.get(this.$store.state.apiList.course,{
            params: {
              id: 123,
            }
          }).then(function (response) {
            // 請求成功回撥函式
          }).catch(function (response) {
            // 請求失敗的回撥函式
          })
}

test(){
          this.$axios.post(this.$store.state.apiList.course,{
              course_title: "Python",
              course_price: "19.88"
          }).then(function (response) {
            // 請求成功回撥函式
          }).catch(function (response) {
            // 請求失敗的回撥函式
          })
}

function getCourse(){
          return this.$axios.get('/course/12')
        }
function getCourse_all() {
          return this.$axios.get('/course')
        }
this.$axios.all([getCourse_all(),getCourse()])
          .then().catch()


methods: {
          init(){
            var that = this
            this.$axios.request({
              url: that.$store.state.apiList.course,
              method: 'get'
            }).then(function (data) {
              if (data.status === 200){
                  that.courseList = data.data
              }
            }).catch(function (reason) {
              console.log(reason)
            })
          }
},