前端-vue路由传参、axios前后台交互、cookie设置

目录

  • 路由传参
    • 标签传参方式:
    • 逻辑传参:this.$router
    • 第一种
    • 第二种
    • 第三种
    • 历史记录跳转
  • 路由汇总大案例
  • vuex仓库
    • 概念
    • 使用
  • axios前后台交互
  • 原生Django提供后台数据
    • 跨域问题
    • django解决跨域问题
    • 数据接口
  • vue-cookie处理cookie
    • element-ui框架使用

路由传参

第一种

router.js
{
    path: '/course/detail/:pk',
    name: 'course-detail',
    component: CourseDetail
}
传递层

详情页
接收层
let id = this.$route.params.pk
演变体
"""
{
    path: '/course/:pk/:name/detail',
    name: 'course-detail',
    component: CourseDetail
}

详情页

let id = this.$route.params.pk
let title = this.$route.params.name
"""

第二种

router.js
{
    // 浏览器链接显示:/course/detail,注:课程id是通过数据包方式传递
    path: '/course/detail',
    name: 'course-detail',
    component: CourseDetail
}
传递层

详情页
接收层
let id = this.$route.params.pk

第三种

router.js
{
    // 浏览器链接显示:/course/detail?pk=1,注:课程id是通过路由拼接方式传递
    path: '/course/detail',
    name: 'course-detail',
    component: CourseDetail
}
传递层

详情页
接收层
let id = this.$route.query.pk

逻辑传参:this.$router

第一种

"""
路由:
path: '/course/detail/:pk'

跳转:id是存放课程id的变量
this.$router.push(`/course/detail/${id}`)

接收:
let id = this.$route.params.pk
"""

第二种

"""
路由:
path: '/course/detail'

跳转:id是存放课程id的变量
this.$router.push({
                    'name': 'course-detail',
                    params: {pk: id}
                });

接收:
let id = this.$route.params.pk
"""

第三种

"""
路由:
path: '/course/detail'

跳转:id是存放课程id的变量
this.$router.push({
                    'name': 'course-detail',
                    query: {pk: id}
                });

接收:
let id = this.$route.query.pk
"""

历史记录跳转

"""
返回历史记录上一页:
this.$router.go(-1)

去向历史记录下两页:
this.$router.go(-2)
"""

路由汇总大案例

router.js
import Vue from 'vue'
import Router from 'vue-router'
import Course from './views/Course'
import CourseDetail from './views/CourseDetail'

Vue.use(Router);

export default new Router({
    mode: 'history',
    base: process.env.BASE_URL,
    routes: [
        {
            path: '/course',
            name: 'course',
            component: Course,
        },
        {
            path: '/course/detail/:pk',  // 第一种路由传参
            // path: '/course/detail',  // 第二、三种路由传参
            name: 'course-detail',
            component: CourseDetail
        },
    ]
})
components/Nav.vue




views/Course.vue




components/CourseCard.vue



views/CourseDetail.vue




vuex仓库

概念

"""
vuex仓库是vue全局的数据仓库,好比一个单例,在任何组件中通过this.$store来共享这个仓库中的数据,完成跨组件间的信息交互。

vuex仓库中的数据,会在浏览器刷新后重置
"""

使用

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_value) {
            console.log(state);
            console.log(new_value);
            state.course_page = new_value;
        }
    },
    actions: {}
})
仓库共享数据的获取与修改:在任何组件的逻辑中
// 获取
let course_page = this.$store.state.course_page

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

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

axios前后台交互

安装:前端项目目录下的终端
>: npm install axios --save
配置:main.js
// 配置axios,完成ajax请求
import axios from 'axios'
Vue.prototype.$axios = axios;
使用:组件的逻辑方法中
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: 'get',  // 请求方式
    }).then(response => {  // 请求成功
        console.log('请求成功');
        console.log(response.data);
        this.course_ctx = response.data;  // 将后台数据赋值给前台变量完成页面渲染
    }).catch(error => {  // 请求失败
        console.log('请求失败');
        console.log(error);
    })
}

原生Django提供后台数据

跨域问题

原理
"""
后台服务器默认只为自己的程序提供数据,其它程序来获取数据,都可能跨域问题(同源策略)

一个运行在服务上的程序,包含:协议、ip 和 端口,所以有一个成员不相同都是跨域问题

出现跨域问题,浏览器会抛 CORS 错误
"""

django解决跨域问题

安装插件
>: pip install django-cors-headers
配置:settings.py
# 注册app
INSTALLED_APPS = [
    ...
    'corsheaders'
]
# 添加中间件
MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware'
]
# 允许跨域源
CORS_ORIGIN_ALLOW_ALL = False

# 设置白名单
CORS_ORIGIN_WHITELIST = [
    # 本机建议就配置127.0.0.1,127.0.0.1不等于localhost
    'http://127.0.0.1:8080',
    'http://localhost:8080',
]

数据接口

路由:urls.py
from django.conf.urls import url
from app import views
urlpatterns = [
    url(r'^course/detail/(?P.*)/', views.course_detail),
]
视图函数:app/views.py
# 模拟数据库中的数据
detail_list = [
    {
        'id': 1,
        'bgColor': 'red',
        'title': 'Python基础',
        'ctx': 'Python从入门到入土!'
    },
    {
        'id': 3,
        'bgColor': 'blue',
        'title': 'Django入土',
        'ctx': '扶我起来,我还能战!'
    },
    {
        'id': 8,
        'bgColor': 'yellow',
        'title': 'MySQL删库高级',
        'ctx': '九九八十二种删库跑路姿势!'
    },
]

from django.http import JsonResponse
def course_detail(request, pk):
    data = {}
    for detail in detail_list:
        if detail['id'] == int(pk):
            data = detail
            break
    return JsonResponse(data, json_dumps_params={'ensure_ascii': False})

vue-cookie处理cookie

安装:前端项目目录下的终端
>: npm install vue-cookie --save
配置:main.js
// 配置cookie
import cookie from 'vue-cookie'
Vue.prototype.$cookie = cookie;
使用:组件的逻辑方法中
created() {
    console.log('组件创建成功');
    let token = 'asd1d5.0o9utrf7.12jjkht';
    // 设置cookie默认过期时间单位是1d(1天)
    this.$cookie.set('token', token, 1);
},
mounted() {
    console.log('组件渲染成功');
    let token = this.$cookie.get('token');
    console.log(token);
},
destroyed() {
    console.log('组件销毁成功');
    this.$cookie.delete('token')
}

element-ui框架使用

安装:前端项目目录下的终端
>: cnpm i element-ui -S
配置:main.js
// 配置element-ui
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);
使用:任何组件的模板中都可以使用 - 详细使用见官方文档




转载于:https://www.cnblogs.com/gaohuayan/p/11443567.html

你可能感兴趣的:(前端,python,javascript)