Vue - warehouse, axios front and back interaction and cross-domain issues

Vuex warehouse

concept

vuex warehouse vue global data warehouse, like a singleton, by this in any assembly. $ store to share this data warehouse, complete information exchange between the cross-component. The equivalent of a temporary warehouse, will be reset after the browser refresh

use

// store.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        // 设置任何组件都能访问的共享数据
        course_page:''
    },
    mutations: {
        // 通过外界的新值来修改仓库中的共享数据的值
        UpdateCoursePage(state,new_page){
            // 只能接收两个参数
            state.course_page=new_page
        }
    },
    actions: {}
})

// 仓库共享数据的获取与修改:在任何组件的逻辑中
// 获取
let cour_page = this.$store.state.course_page

// 直接修改
this.$store.state.course_page = '新值'

// 方法修改
this.$store.commit('UpdateCoursePage','新值')

Taiwan before and after the interaction axios

Installation: at the front end of the terminal project directory

npm install axios --save

Configuration: main.js

// 配置axios,完成ajax请求
import axios from 'axios'
Vue.prototype.$axios = axious;

Use: logical methods assembly

created(){  // 组件创建成功的钩子函数
    // 拿到要访问课程详情的课程id
    let id = this.$route.params.pk || this.$route.query.pk||1
    this.$axios({
        url:`http://127.0.0.1:8000/course/detail/${id}`,  // 后台接口
        method:'POST',  // 请求方式
    }).then(response => {  // 请求成功
        console.log('请求成功')
        console.log(response)
        this.course_ctx = response.data;  // 将后台数据赋值给前台变量完成页面渲染
    }).catch(error =>{  // 请求失败
        console.log('请求失败')
        console.log(error)
    })
}

Cross-domain issues

principle

Background server by default only provide data for their own programs, other programs to obtain the data, may cross-domain issues

A run on the service procedures, including: the agreement, ip, port, so there are not the same as a member of the cross-domain issues. Cross-domain problem occurs, the browser will throw an error CORS

django solve cross-domain problems

1) Plug
pip install django-cors-headers
2) configuration file settings.py
# 注册app
INSTALLED_APPS = [
    'corsheaders'
]
# 添加中间件
MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware'
]
# 允许跨域源,True表示允许所有跨域源
CORS_ORIGIN_ALLOW_ALL = False  

# 设置白名单,允许跨域的白名单
CORS_ORIGN_WHITELIST = [
    # 本机建议就配置127.0.0.1,127.0.0.1不等于localhost
    'http://127.0.0.1:8080',
    'http://localhost:8080',
]

Guess you like

Origin www.cnblogs.com/863652104kai/p/11443750.html