VUE(四)
一.路由汇总
import Vue from 'vue' import Router from 'vue-router' import PageFirst from './views/PageFirst' import PageSecond from './views/PageSecond' 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: [ // 路由就是 url路径 与 vue组件 的映射关系 // 映射出的组件会替换 根组件 中的 router-view 标签 // 通过 router-link 标签完成 url路径 的切换 { path: '/page-first', name: 'page-first', component: PageFirst }, { path: '/page/first', redirect:{'name':'page-first'} }, { path: '/page-second', name: 'page-second', component: PageSecond }, { path: '/course', name: 'course', component: Course }, { // path: '/course/detail/:pk', // 第一种路由传参 path: '/course/detail', // 第二、三种路由传参 name: 'course-detail', component: CourseDetail }, ] })
二.课程详情页面组件CourseDetail.vue通过点击CourseCard.vue中内容获取id渲染
let id = this.$route.params.pk || this.$route.query.pk;
( $route.params 数据包方式向后台发送,或者有名分组 $route.query 路由路径拼接)
<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>
三.CourseCard.vue中的跳转
首先,CourseCard中的数据是组件父传子传进来的,也就是从Course中拿到的(需要导入,注册,渲染)
Course.vue:
<template>
<div class="course">
<Nav></Nav>
<h1>课程主页</h1>
<CourseCard :card="card" v-for="card in card_list" :key="card.tytle"></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>
CourseCard.vue逻辑跳转(通过go可实现前后跳转):
<template>
<div class="course-card">
<div class="left" :style="{background: card.bgColor}"></div>
<div class="right" @click="goto_detail">{{ card.title }}</div>
</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;
}
.course-card div {
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;
}
</style>
CourseCard.vue链接跳转:
<template>
<div class="course-card">
<div class="left" :style="{background: card.bgColor}"></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'],
}
</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;
}
</style>
链接转调演变体:
""" { 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 """
四.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', '新值');
案例:
course.vue:
data() { return { card_list: [], course_page: this.$store.state.course_page || '课程主页' // course_page: sessionStorage.course_page || '课程主页' } },
coursedetail.vue
methods:{ editAction(){ if (this.val){ console.log(this.val) // sessionStorage.course_page=this.val // this.$store.state.course_page=this.val this.$store.commit('updateCoursePage', this.val); this.$router.push('/course') // this.$router.go(-1) } }
五.后台发送数据
url.py:
url(r'^course/detail/(?P<pk>.*)/', views.course_detail),
views.py:
from django.shortcuts import render,HttpResponse,redirect from django.http import JsonResponse detail_list = [ { 'id': 1, 'bgColor': 'red', "title": "Python基础", 'ctx': 'Python从入门到入土!' }, { 'id': 3, 'bgColor': 'blue', 'title': 'Django入土', 'ctx': '扶我起来,我还能战!' }, { 'id': 8, 'bgColor': 'yellow', 'title': 'MySQL删库高级', 'ctx': '九九八十二种删库跑路姿势!' }, ] # Create your views here. 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})
npm install axios --save
// 配置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);
})
}
后台服务器默认只为自己的程序提供数据,其它程序来获取数据,都可能跨域问题(同源策略)
一个运行在服务上的程序,包含:协议、ip 和 端口,所以有一个成员不相同都是跨域问题
出现跨域问题,浏览器会抛 CORS 错误
pip install django-cors-headers
# 注册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', ]
cnpm install vue-cookie --save
// 配置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') }
九.
cnpm i element-ui -S
// 配置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>

浙公网安备 33010602011771号