VUE 之 vuex 和 axios

1、Vuex 部分

  1.1 Vuex 是专门为vue.js设计的集中式状态管理架构,其实就是将数据存在一个store中,共各个组件共享使用

  1.2 配置:

    1.2.1 下载:--npm install vuex

    1.2.2 导入:import Vuex(这个名字随便起) from "vuex"

    1.2.3 使用:Vue.use(Vuex)  

    1.2.4 实例化仓库对象:new store({ 属性名(state,getters,mutation)})  

import Vue from "vue"
import Vuex from "vuex"

Vue.use(Vuex);


export default new Vuex.Store({
    // this.$store.state.name       # 这个store是在Vue根实例中注册的store
    state: {
      name: "xiaodilei"
    },
    // this.$store.getters.new_name
    getters: {
       new_name: function (state) {
          return state.name + "爆炸了"
       },
       new_new_name: function (state, getters) {
          return getters.new_name + "duang~~"
       }
    },
    mutations: {
      change_data: function (state, data) {
          // 自己处理change_data事件的
         console.log(state.name)
         console.log(data)
          state.name = data;
      }
    }
})

    1.2.5 在Vue 根实例中注册sotre

new Vue({
   el:"#app",
   store  
})

  1.3 获取vuex中的数据

    this.$store.state.属性名

    this.$store.getters.属性名

  1.4改变vuex中的数据

    1.4.1 首先组件要想仓库提交事件

      this.$store.commit("事件名称",要修改成的结果)

    1.4.2 仓库要处理提交的事件

      mutations: {
            "事件名称": function(state, data){
            修改state中的数据  
                      }
            }

2、axios部分

  2.1 用来发送ajax请求的

  2.2 配置:

    2.1 下载:npm install axios

    2.2 导入:import axios from 'axios'

    2.3 加入原型链:Vue.prototype.$axios = axios

  2.3 在组件中发送请求

    this.$axios.request({

              url:'127.0.0.1',

              method:get,

              data,

              headers

               }).then(function(data){}).catch(function(data){})

    

 mounted(){
          let that = this;           注意this
           this.$axios.request({
               url: "http://127.0.0.1:8000/demo",
               method: "get"
           }).then(function (data) {
              // do something~~
              that.msg = data.data      这里应该用msg的this
              console.log(data)
           }).catch(function (data) {
              // do something~~
           })

          // this.$axios.get("url",{}).then().catch()
        }

  2.4 跨域问题

    前后端进行连接的时候,由于url的不同,发送了一个option请求,导致出现跨域问题。

    这时需要创建一个中间件来解决这个问题

from django.utils.deprecation import MiddlewareMixin


class MyCors(MiddlewareMixin):
    def process_response(self, request, response):       自定义一个响应头就可以解决
        response["Access-Control-Allow-Origin"] = "*"
        return response
原文地址:https://www.cnblogs.com/wf123/p/9965060.html