Vuex與axios介紹

Vuex集中式狀態管理架構

 -簡單介紹:前端

vuex是一個專門爲Vue.js設計的集中式狀態管理架構。
咱們把它理解爲在data中須要共享給其餘組件使用的部分。

Vuex和單純的全局對象有如下不一樣:

1、Vuex 的狀態存儲是響應式的。當vue組件從store中讀取狀態的時候,
  若store中的狀態發生變化,那麼相應的組件也會相應的獲得高效更新。

2、你不能直接改變store中的狀態。改變store中的狀態的惟一途徑就是顯示的
  提交(commit)mutation。這樣使得咱們能夠方便的跟蹤每個狀態的變化,
  從而讓咱們可以實現一些工具來幫助咱們更好的瞭解咱們的應用。

3、或者能夠說,它就是前端裏面簡單替代數據庫來存儲數據的一個架構;

- 安裝使用:vue

  - npm直接下載:npm install vuexnode

 

  - 使用:ios

複製代碼
// 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/>'
});
複製代碼

 

  - 將vuex解耦出來,放到src文件夾下的store.js文件裏面:ajax

複製代碼
// store.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/>'
});
複製代碼

 

  - Vuex.Store 對象中存在的三個屬性:state,getters,mutationsvuex

    - state:保存咱們data中須要共享的數據數據庫

      - 獲取state中的數據最好的方法是使用 計算屬性,由於計算屬性能夠存在內存中,讀取速度快,正常的data 也可獲取;npm

      - 獲取state的語法:this.$store.state.countaxios

      - 示例:api

複製代碼
// 建立組件
const Counter = {
  template: `<div>{{ count }}</div>`,
  // 計算屬性 computed
    computed: {
    count(){
      return this.$store.state.count
    }
  }
};
複製代碼

 

    - getters:該屬性對應的是一個對象,對象中存放函數,該函數的返回值會保存在內存中,可是,當函數中的依賴關係發生改變時,它的返回結果會隨之改變;類如計算屬性;

      - 獲取getters中對應的函數的值:this.$store.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
    }
  },

});
複製代碼

 

    - mutations:當想讓store中的state的值的發生變化時,須要提交mutation中定義了的函數,纔可發生變化;(更改store中的狀態的方法)

      - 每一個mutations對應的函數都須要接收 一個字符串的事件類型(type),和一個回調函數handler。

      - 觸發mutations中的函數的語法:this.$store.commit('定義的函數', 函數須要的值);

      - 示例:

複製代碼
import Vue from 'vue'
import Vue_x from "vuex"

Vue.use(Vue_x);

export default  new Vue_x.Store({
   state: {
     count: 20,
   },
  // 須要經過 this.$store.commit('increment', 10)
  mutations: {
     increment (state, n) {
       // 變動狀態
       state.count += n
     }
  }

});
複製代碼

 

      - mutations須要遵照Vue的響應規則

複製代碼
既然vuex中的store中的狀態是響應式的,那麼當咱們狀態變動時,監視狀態的vue組件也會更新。

這就意味着vuex中的mutation也須要與使用vue同樣遵照一些注意事項:

  -- 1,最好提早在你的store中初始化好全部的所須要的屬性

  -- 2,當對象須要添加屬性時,你應該使用

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

      --  以新對象代替老對象  state.obj = { ...state.obj, newProp: 123}
複製代碼

axios   (Ajax)

 

- 介紹:

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

基本上就是又進行了一層封裝的ajax

- 安裝:

npm install axios -D

- 基本配置:

  - 在Vue對象中加載 axios : Vue.prototype.$axios = axios

// main.js
import Vue from 'vue'
import axios from "axios"

Vue.prototype.$axios = axios

  - 正常的 axios請求 基本上綁定在組件中的方法中;也就是用在 組件對象中的 methods屬性中綁定的各類方法裏面;例如,綁定點擊事件發送GET請求到後臺

複製代碼
// 組件對象:

{
        name: "Home",
        data(){
            return {
                test: ""
            }
        },
        methods: {
            my_click: function (){
                // 改變倉庫中的數據
                this.$store.commit("sale", "一塊錢包年~~")
            },
            // 綁定的點擊事件:
            course_click: function () {
                // 這裏須要注意 this的問題,axios支持鏈式操做,
                // 在操做中的this 會丟失當前對象,將當前對象提早賦值,好在後面繼續使用
                let that = this;
                this.$axios.request({
                    url: "http://127.0.0.1:8000/test/",  //  url: 發送到後臺的地址;
                    method: "get"              // method: "發送的方式";
                }).then(function (data) {         // then: 當請求成功返回後執行這個函數;
                    console.log(data.data);
                    console.log(this);
                    that.test = data.data
                }).catch(function (data) {         // catch: 當請求失敗返回時執行這個函數;
                    console.log(data)
                })
            }
        },

    }
複製代碼

 

- this.$axios 中的 get,post,request,以及發送多個請求的方法all:

  - get請求:

複製代碼
// 組件中的 methods:
// this.$store.state.apiList.course = url信息
// params: 路徑上附帶的參數     ?id=123

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

 

  - post 請求:

複製代碼
// 組件中的 methods:
// this.$store.state.apiList.course = url信息
// {course_title:"Python"}... post請求的請求體數據

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

 

  - request 請求方法:

複製代碼
// this.$axios.request({}) 方法中須要傳入url 和method

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)
            })
          }
},
複製代碼

 

  - all: 併發發送多個請求:

複製代碼
// 定義多個請求,將定義好的函數 放到數組中,當成參數傳到下面的函數裏
// 在組件中的methods中 用 this.$axios.all([請求1,請求2]) 函數 發過去;
// then() 接受成功執行;
// catch() 接受失敗後執行;


function getCourse(){
          return this.$axios.get('/course/12')
        }
function getCourse_all() {
          return this.$axios.get('/course')
        }
this.$axios.all([getCourse_all(),getCourse()])
          .then().catch()
相關文章
相關標籤/搜索