首页 > 技术文章 > Vuex与axios介绍

liuafan 2018-11-21 19:05 原文

Vuex集中式状态管理架构

 -简单介绍:

vuex是一个专门为Vue.js设计的集中式状态管理架构。
我们把它理解为在data中需要共享给其他组件使用的部分。

Vuex和单纯的全局对象有以下不同:

1、Vuex 的状态存储是响应式的。当vue组件从store中读取状态的时候,
  若store中的状态发生变化,那么相应的组件也会相应的得到高效更新。

2、你不能直接改变store中的状态。改变store中的状态的唯一途径就是显示的
  提交(commit)mutation。这样使得我们可以方便的跟踪每一个状态的变化,
  从而让我们能够实现一些工具来帮助我们更好的了解我们的应用。

3、或者可以说,它就是前端里面简单替代数据库来存储数据的一个架构;

- 安装使用:

  - npm直接下载: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/>'
});
复制代码

 

  - 将vuex解耦出来,放到src文件夹下的store.js文件里面:

复制代码
// 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,mutations

    - state:保存我们data中需要共享的数据

      - 获取state中的数据最好的方法是使用 计算属性,因为计算属性可以存在内存中,读取速度快,正常的data 也可获取;

      - 获取state的语法:this.$store.state.count

      - 示例:

复制代码
// 创建组件
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()

 

推荐阅读