Vue-路由传参

路由传参

类似于django,vue也有路由系统,进行路由的分发,有三种传参方式

路由传参方式:<router-link></router-link>

  • 第一种:通过有名分组进行传参

    router.js

    {
        path: '/course/detail/:pk',
        name: 'course-detail',
        component: CourseDetail
    }
    

    传递层

    <!-- card的内容
    {
    	id: 1,
    	bgColor: 'red',
    	title: 'Python基础'
    }
    -->
    <router-link :to="`/course/detail/${card.id}`">详情页</router-link>
    

    接收层

    let id = this.$route.params.pk
    

    演变体

    """
    {
        path: '/course/:pk/:name/detail',
        name: 'course-detail',
        component: CourseDetail
    }
    
    <router-link :to="`/course/${card.id}/${card.title}/detail`">详情页</router-link>
    
    let id = this.$route.params.pk
    let title = this.$route.params.name
    """
    
  • 第二种:通过数据包的方式进行传参

    router.js

    {
        // 浏览器链接显示:/course/detail
        path: '/course/detail',
        name: 'course-detail',
        component: CourseDetail
    }
    

    传递层

    <router-link :to="{
                      name: 'course-detail',
                      params:{pk:card.id},
                      }">详情页</router-link>
    

    接收层

    let id = this.$route.params.pk
    
  • 第三种:通过qurey进行传参,通过路由拼接方式传参

    router.js

    {
         // 浏览器链接显示:/course/detail?pk=1
        path: '/course/detail',
        name: 'course-detail',
        component: CourseDetail
    }
    

    传递层

    <router-link :to="{
                      name: 'course-detail',
                      query:{pk:card.id},
                      }">详情页</router-link>
    

    接收层

    let id = this.$route.query.pk
    

逻辑传参

通过router进行传参

  • 第一种

    """
    路由:
    path: '/course/detail/:pk'
    
    跳转:id是存放课程id的变量
    this.$router.push(`/course/detail/${id}`)
    
    接收:
    let id = this.$route.params.pk
    """
    
  • 第二种:通过param数据包的方式

    """
    路由:
    path: '/course/detail'
    
    跳转:id是存放课程id的变量
    this.$router.push({
                        'name': 'course-detail',
                        params: {pk: id}
                    });
    
    接收:
    let id = this.$route.params.pk
    """
    
  • 第三种:通过query的方式

    """
    路由:
    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)
"""

vuex仓库

概念

vuex仓库就是vue全局的数据仓库,在任何组件中都可以通过this.$store来共享这个仓库中的数据,完成跨组件间的信息交互,不同于sessionStorage和localStorage,它会在浏览器刷新后进行重置

  • sessionStorage:页面关闭,数据清空
  • localStorage:数据永久保存
  • 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);
        })
    }
    

跨域问题

主要就是因为前后端分离,前台需要从后台获取数据,但是后台服务器默认只为自己的程序提供数据,对于其他程序的请求,都会造成跨域问题,浏览器会报 CORS 错误

只有协议、IP和端口都一样的时候,才不会造成跨域问题

Django解决跨域问题

  • 第一步:安装插件

    pip install django-cors-headers

  • 第二步:在settings中进行配置

    # 注册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',
    ]
    

原生Django提供后台数据

  • 第一步:配置路由

    from django.conf.urls import url
    from app import views
    urlpatterns = [
        url(r'^course/detail/(?P<pk>.*)/', views.course_detail),
    ]
    
  • 第二步:写视图函数,返回数据

    # 模拟数据库中的数据
    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})
    

路由案例

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

<template>
    <div class="nav">
        <router-link to="/page-first">first</router-link>
        <router-link :to="{name: 'page-second'}">second</router-link>
        <router-link to="/course">课程</router-link>
    </div>
</template>

<script>
    export default {
        name: "Nav"
    }
</script>

<style scoped>
    .nav {
        height: 100px;
        background-color: rgba(0, 0, 0, 0.4);
    }
    .nav a {
        margin: 0 20px;
        font: normal 20px/100px '微软雅黑';
    }
    .nav a:hover {
        color: red;
    }
</style>

views/Course.vue

<template>
    <div class="course">
        <Nav></Nav>
        <h1>课程主页</h1>
        <CourseCard :card="card" v-for="card in card_list" :key="card.title"></CourseCard>
    </div>
</template>

<script>
    import Nav from '@/components/Nav'
    import CourseCard from '@/components/CourseCard'
    export default {
        name: "Course",
        data() {
            return {
                card_list: [],
            }
        },
        components: {
            Nav,
            CourseCard
        },
        created() {
            let cards = [
                {
                    id: 1,
                    bgColor: 'red',
                    title: 'Python基础'
                },
                {
                    id: 3,
                    bgColor: 'blue',
                    title: 'Django入土'
                },
                {
                    id: 8,
                    bgColor: 'yellow',
                    title: 'MySQL删库高级'
                },
            ];
            this.card_list = cards;
        }
    }
</script>

<style scoped>
    h1 {
        text-align: center;
        background-color: brown;
    }
</style>

components/CourseCard.vue

<template>
    <div class="course-card">
        <div class="left" :style="{background: card.bgColor}"></div>
        <!-- 逻辑跳转 -->
        <div class="right" @click="goto_detail">{{ card.title }}</div>
        
        <!-- 链接跳转 -->
        <!-- 第一种 -->
        <!--<router-link :to="`/course/detail/${card.id}`" class="right">{{ card.title }}</router-link>-->
        <!-- 第二种 -->
        <!--<router-link :to="{-->
            <!--name: 'course-detail',-->
            <!--params: {pk: card.id},-->
        <!--}" class="right">{{ card.title }}</router-link>-->
        <!-- 第三种 -->
        <!--<router-link :to="{-->
            <!--name: 'course-detail',-->
            <!--query: {pk: card.id}-->
        <!--}" class="right">{{ card.title }}</router-link>-->
    </div>
</template>

<script>
    export default {
        name: "CourseCard",
        props: ['card'],
        methods: {
            goto_detail() {
                // 注:在跳转之前可以完成其他一些相关的业务逻辑,再去跳转
                let id = this.card.id;
                // 实现逻辑跳转
                // 第一种
                this.$router.push(`/course/detail/${id}`);
                // 第二种
                // this.$router.push({
                //     'name': 'course-detail',
                //     params: {pk: id}
                // });
                // 第三种
                // this.$router.push({
                //     'name': 'course-detail',
                //     query: {pk: id}
                // });

                // 在当前页面时,有前历史记录与后历史记录
                // go(-1)表示返回上一页
                // go(2)表示去向下两页
                // this.$router.go(-1)
            }
        }
    }
</script>
<style scoped>
    .course-card {
        margin: 10px 0 10px;
    }
    .left, .right {
        float: left;
    }
    .course-card:after {
        content: '';
        display: block;
        clear: both;
    }
    .left {
         50%;
        height: 120px;
        background-color: blue;
    }
    .right {
         50%;
        height: 120px;
        background-color: tan;
        font: bold 30px/120px 'STSong';
        text-align: center;
        cursor: pointer;
        display: block;
    }
</style>

views/CourseDetail.vue

<template>
    <div class="course-detail">
        <h1>详情页</h1>
        <hr>
        <div class="detail">
            <div class="header" :style="{background: course_ctx.bgColor}"></div>
            <div class="body">
                <div class="left">{{ course_ctx.title }}</div>
                <div class="right">{{ course_ctx.ctx }}</div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        name: "CourseDetail",
        data() {
            return {
                course_ctx: '',
                val: '',
            }
        },
        created() {
            // 需求:获取课程主页传递过来的课程id,通过课程id拿到该课程的详细信息
            // 这是模拟后台的假数据 - 后期要换成从后台请求真数据
            let detail_list = [
                {
                    id: 1,
                    bgColor: 'red',
                    title: 'Python基础',
                    ctx: 'Python从入门到入土!'
                },
                {
                    id: 3,
                    bgColor: 'blue',
                    title: 'Django入土',
                    ctx: '扶我起来,我还能战!'
                },
                {
                    id: 8,
                    bgColor: 'yellow',
                    title: 'MySQL删库高级',
                    ctx: '九九八十二种删库跑路姿势!'
                },
            ];
            // let id = 1;
            // this.$route是专门管理路由数据的,下面的方式是不管哪种传参方式,都可以接收
            let id = this.$route.params.pk || this.$route.query.pk;
            for (let dic of detail_list) {
                if (dic.id == id) {
                    this.course_ctx = dic;
                    break;
                }
            }
        }
    }
</script>

<style scoped>
    h1 {
        text-align: center;
    }
    .detail {
         80%;
        margin: 20px auto;
    }
    .header {
        height: 150px;
    }
    .body:after {
        content: '';
        display: block;
        clear: both;
    }
    .left, .right {
        float: left;
         50%;
        font: bold 40px/150px 'Arial';
        text-align: center;
    }
    .left { background-color: aqua }
    .right { background-color: aquamarine }

    .edit {
         80%;
        margin: 0 auto;
        text-align: center;

    }
    .edit input {
         260px;
        height: 40px;
        font-size: 30px;
        vertical-align: top;
        margin-right: 20px;
    }
    .edit button {
         80px;
        height: 46px;
        vertical-align: top;
    }
</style>
原文地址:https://www.cnblogs.com/Hades123/p/11454752.html