bladecheng

路由传参

传参方式

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,注:课程id是通过数据包方式传递
    path: \'/course/detail\',
    name: \'course-detail\',
    component: CourseDetail
}

传递层

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

接收层

let id = this.$route.params.pk

第三种

router.js

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

传递层

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

接收层

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

<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 {
        width: 50%;
        height: 120px;
        background-color: blue;
    }
    .right {
        width: 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 {
        width: 80%;
        margin: 20px auto;
    }
    .header {
        height: 150px;
    }
    .body:after {
        content: \'\';
        display: block;
        clear: both;
    }
    .left, .right {
        float: left;
        width: 50%;
        font: bold 40px/150px \'Arial\';
        text-align: center;
    }
    .left { background-color: aqua }
    .right { background-color: aquamarine }

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

    }
    .edit input {
        width: 260px;
        height: 40px;
        font-size: 30px;
        vertical-align: top;
        margin-right: 20px;
    }
    .edit button {
        width: 80px;
        height: 46px;
        vertical-align: top;
    }
</style>

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<pk>.*)/\', 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.$axios = 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);

使用:任何组件的模板中都可以使用 - 详细使用见官方文档

<template>
    <div class="e-ui">
        <Nav></Nav>
        <h1>element-ui</h1>
        <hr>

        <el-row :gutter="10">
            <el-col :span="6">
                <div class="grid-content bg-purple"></div>
            </el-col>
            <el-col :span="6">
                <div class="grid-content bg-purple"></div>
            </el-col>
            <el-col :span="10" :offset="2">
                <div class="grid-content bg-purple"></div>
            </el-col>
        </el-row>

        <el-container>
            <el-main>
                <el-row :gutter="10">
                    <el-col :sm="18" :md="12" :lg="6">
                        <div class="grid-content bg-purple"></div>
                    </el-col>
                    <el-col :sm="6" :md="12" :lg="18">
                        <div class="grid-content bg-purple"></div>
                    </el-col>
                </el-row>
            </el-main>
        </el-container>

        <el-row>
            <i class="el-icon-platform-eleme"></i>
            <el-button type="primary" @click="alertAction1">信息框</el-button>
            <el-button type="success" @click="alertAction2">弹出框</el-button>
        </el-row>
    </div>
</template>

<script>
    import Nav from \'@/components/Nav\'

    export default {
        name: "EUI",
        components: {
            Nav
        },
        methods: {
            alertAction1() {
                this.$message({
                    type: \'success\',
                    message: \'message信息\',
                })
            },
            alertAction2() {
                this.$alert(\'内容...\', \'标题\')
            },
        }
    }
</script>

<style scoped>
    .e-ui {
        width: 100%;
        height: 800px;
        background: pink;
    }

    h1 {
        text-align: center;
    }

    .grid-content {
        height: 40px;
        background-color: brown;
        margin-bottom: 10px;
    }

    i {
        font-size: 30px;
    }
</style>

分类:

技术点:

相关文章: