路由傳參
標簽傳參方式:<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,注:課程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.$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);
使用:任何組件的模板中都可以使用 - 詳細使用見官方文檔
<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>