Vue :前后端分离的框架, 目前全球最流行的前端框架,使用vue 开发网页很简单,并且技术生态环境完善,社区活跃。
Vue安装与使用
- 方式1 :通过sript标签引用
- 方式2 :通过npm(node package manager) 来安装
- 方式3 : 通过vue-cli命令行来安装
# 通过sript标签引用
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
# 将Vue.js 保存在本地
<script src="./vue.js"></script>
基本使用
# 1、创建 Vue 对象,并向对象中传递 el 参数,el 参数全称 element,用来找到一个给Vue渲染的根元素。
# 2、可以传递一个data 参数,data中所有的值都可以直接在根元素下使用 {{}} 来使用
# el 标签 绑定
# data 传递数据
# method 传递方法()
<div id="app">
<p>{{username}}</p>
# 只变化一次 v-once
<p v-once>{{username}}</p>
# 显示原生的HTML v-html
<p v-html="code">{{code}}</p>
# 绑定属性 v-bind, 属性不需要用{{}}包裹 src为属性
<img v-bind:src="imagesrc" alt="">
#同上 绑定属性
<img :src="imagesrc" alt="">
<p>{{demo(username)}}</p>
</div>
<script>
# Vue 对象
let vm = new Vue({
# 绑定 # = id (上面div标签的id)
el:"#app",
# 所需传输数据
data:{
# 数据传入到{{username}}
"username":"lcl",
# 页面中 显示原生的HTML v-html
"code":"<a href='https://www.baidu.com/'>百度一下</a>",
# 绑定属性 v-bind
"imagesrc":"https:baidu.com/img/bd_logo1.png?qua=high&where=super"
},
# 传递方法
methods:{
demo:function(name){
return "晚上好" + this.username # this 用来访问data内的数据
}
}
});
</script>
Vue模板语法
在html中通过 {{}} 可以将Vue对象中的数据插入到网页中,只要Vue对象的值发生变化,html中 {{}} 的值也会立马变化
# **一次绑定 v-once**
<div id="app">
<p v-once>{{username}}</p> # 第一次渲染后,不想根后期数据更改而更改,可以用v-onece 实现
</div>
<script>
# Vue 对象
let vm = new Vue({
# 绑定 # = id (上面div标签的id)
el:"#app",
# 数据传入到{{username}}
data:{
"username":"lcl",
},
});
</script>
# **对原声的html代码进行渲染**
<div id="app">
<div v-html="code">{{code}}</div>
</div>
<script>
let vm = new Vue({
# 绑定 # = id (上面div标签的id)
el:"#app",
data:{
"code":"<a href='https://www.baidu.com/'>百度一下,你就知道!</a>"
}
});
</script>
# **属性绑定 V-bind**
# html元素属性绑定Vue对象中的变量,通过V-bind来实现
<div id="app">
<img v-bind:src="imgSrc" alt="">
<img :src="imgSrc" alt="">
</div>
<script>
let vm = new Vue({
el: "#app",
data: {
"imgSrc": "https://i.ytimg.com/vi/5HKZ6bU6Zg0/maxresdefault.jpg"
}
});
</script>
# **绑定class或 style**
# 1、绑定class —— v-bind 绑定
<head>
<style>
.title{ font-size : 200px;
color : red;}
.main-title{ font_wight :800
}
</style>
</head>
<body>
<div id="app">
<p v-bind:class="classname1">你好,世界</p> #绑定1个属性
<p v-bind:class="[classname1,classname2]">你好,世界</p> # 绑定2个属性
<p v-bind:class="class1">你好,世界</p> #通过class1 绑定2个属性
<p v-bind:class="{ title:class3,'main-title':class4}">你好,世界</p> # 通过对象的方式实现
</div>
</body>
<script>
let vm = new Vue({
el: "#app",
data: {
classname1: "title",
classname2: "main-title",
class1 : "title main-title",
# 通过对象的方式实现
class3: true,
class4: true,
}
});
</script>
绑定
#绑定<style> v-bin:style - 用对象方式
<body>
<div id="app">
<p v-bind:style="{backgroudColor:background}"> 内容 </p>
<p v-bind:style="{'backgroudcolor':background}"> 内容1 </p>
<p v-bind:style="liStyle"> 内容2的 </p>
# 数组方式绑定
<p v-bind:style="[liStyle,liStyle2]"> 内容2 </p>
</div>
</body>
<script>
new Vue({
el: "#app",
data: {
liStyle: {
backgroundColor: "red",
fontSize: "14px"
},
liStyle2: {
fontWeight: 800
},
background : 'red';
}
})
</script>
使用JavaScript表达式(JS)
# <p>标签中三元运算符 如果color为ture则显示红色,否则显示蓝色
# 将传递过来的username进行split切割,然后reverse反转,最后在变更为字符串
<body>
<div>
# username数据反转 - 按照空格切割、反转、组合
<p>{{username.split(" ").reverse(),join(" ")}}</p>
# 三元运算 如果color 为true 则为红色,否则为蓝色
<p v-bind:style="{color:color?'red':'bilue'}">{{username}}</p>
</div>
</body>
<script>
new Vue({
el: "#app",
data: {
username : 'hello world',
color :False #也 可以写 0,1
}
})
</script>
# **多条件判断**
# div#app div id = "app"
# div.app div class = "app"
# v-if、v-else-if、以及v-else 来组合实现
<div id = "app">
<p v-if="weather =='sun'">今天去公园玩</p>
<p v-else-if="weather =='rain'">今天去看电影</p>
<p v-else>今天哪也不去</p>
<template v-if="age<18">
<p>上网、逃学</p>
</template>
<template v-else-if="age>=18 && age<25">
<p>找女友</p>
</template>
<template v-else>
<p>找工作</p>
</template>
</div>
<script>
new Vue({
el: "#app",
data: {
weather:'sun',
age : 18
}
})
</script>
# **切换登陆方式** —— 账号密码登陆 VS 手机号动态登陆
<div id = "app">
<template v-if ="loginType== 'username'">
<label for="">用户名:</label>
# key属性每次刷新时重新渲染,placeholder="用户名"默认提示值
<input type="text" placeholder="用户名" key="usernamekey">
</template>
<template v-else-if ="loginType== 'email'">
<label for="">邮箱:</label>
<input type="text" placeholder="邮箱" key ="emailkey">
</template>
<button v-on:click="changeLoginType">切换登陆类型</button> # 绑定一个点击事件
<button @click="changeLoginType">切换登陆类型</button> # 绑定一个点击事件
</div>
<script>
new Vue({
el: "#app",
data: {
loginType : 'email'
},
methods:{
changeLoginType:function(){ this.loginType=this.loginType=='username'?'email':'username'
}
}
})
</script>
# **for 循环**
<div id = "app">
<tr>
<th>序号</th>
<th>标题</th>
<th>作者</th>
</tr>
<tr v-for="(book,index) in books">
<td>{{index+1}}</td>
<td>{{book.title}}</td>
<td>{{book.author}}</td>
</tr>
<div v-for="(value,key) in person">
{{value}}
{{key}}
</div>
</div>
<script>
new Vue({
el: "#app",
data: {
weather:'sun'
books:[
{
'title':'python',
'author':'guishu'
},
{
'title':'java',
'author':'buzhidao'
},
{
'title':'php',
'author':'buzhidao'
},
],
person:{
"username":"lcl",
"age":18,
"address":"bj"
},
},
}
})
</script>
# 数据保持
# 循环出来的元素,如果没有使用key元素来唯一标识,如果后期的数据发生更改,默认会重用,并且元素的顺序不会跟着数据的顺序更改而更改
<div id = "app">
<div v-for="book in books" v-bind:key = "book"> # v-bind:key = "book" 123 保持
<label>{{book}}</label>
<input type ='text' v-bind:placeholder="book">
</div>
<button @click="changeBooks">更换图书</button>
</div>
<script>
new Vue({
el: "#app",
data: {
books:['python','java','php','c++']
},
methons:{
changeBooks:function(){
this.books.sort(funcion(a,b){
# 正数 true 负数 false
return 5-Math.random()*10}
)}
}
})
</script>
vue触发视图的更新
# Vue 对一些方法进行包装和变异,以后数组通过这些方法进行数组的更新,会触发视图更新
<div id = "app">
<div v-for="book in books" v-bind:key = "book">
<label>{{book}}</label>
<input type ='text' v-bind:placeholder="book">
</div>
<button @click="updatelist">更新数组</button>
</div>
<script>
new Vue({
el: "#app",
data: {
books:['python','java','php','c++'],
person:{
username:'lcl',
},
},
methods:{
updatelist:function(){
# 直接赋值-将books 的内容更改为 lcl
this.books = ['lcl']
this.person.username = 'wzh'
# 将元素推入books中,放在最后
this.books.push("redis")
# 删除books数组最后一个
this.books.pop()
# 删除books第一个元素
this.books.shift()
# 在数组的开头位置添加一个元素
unshift(item) # this.books.unshift("lcl")
# 向数组中下标index开始,替换howmany个元素
this.splice(index,howmany,item1,...itemx)
# 向books第0个位置添加元素
this.books.splice(0,0,"内容1")
# 下标从0开始,删除2个元素
this.books.splice(0,2)
# 下标从0开始,替换2个元素
this.books.spice(0,2,"内容1","内容2")
# 排序
this.books.sort(function(a,b){
# 取两个随机数进行排序
a = Math.random()
b = Math.random()
return a-b
})
#将数组进行元素反转
this.books.reverse()
# 更改列表中的某一个值- 第一个值改成lcl
Vue.set(this.books,1,'lcl')
# 更新对象中的值(字典格式)
this.person.username= 'lcl'
# 在对象中添加属性(字典格式)添加 age :18
Vue.set(this.person,'age',18)
)}
}
})
</script>
绑定事件 v-on 或 @
<div id = "app">
<p>{{count}}</p>
# 点击事件、点击一次加 1
<button v-on:click="count+=1"> 加 </button>
# 点击事件,点击一次减 1
<button @click="sub"> 减 </button>
</div>
<script>
new Vue({
el: "#app",
data: {
count : 0
}
methons:{
# 写入方式1:
sub(){
this.count -=1 }
},
# 写入方式 2
sub:function(){
this.count -=1
},
}
})
</script>
传入event 参数
"""
如果再事件处理函数中,想要获取原生的DOM事件,那么再html代码中,调用的时候,可以传入一个$event 参数
"""
<div id = "app">
<p>{{count}}</p>
<button v-on:click="cout+=1"> 加 </button>
#
<button @click="sub(2,$event)" value ='lcl' name = 'Lcl'> 减 </button>
</div>
<script>
new Vue({
el: "#app",
data: {
books:['python','java','php','c++']
},
methons:{
sub:function(value,event){
# event 主要获取点击事件中包含的属性,如:value、name 属性
console.log(event.target.value)
console.log(event.target.name)
this.count -=value
},
}
})
</script>
**计算属性 **
# v-model 双向绑定 / 计算属性 computed
<div id = "app">
<label>长:</label>
# v-model 双向绑定
<input type ='number' name="length" v-model:value="length">
# <input type ='number' name="length" v-model="length"> 简写方式
<label>宽:</label>
<input type ='number' name="width" v-model:value="width">
<label>面积:</label>
<input type ='number' readonly v-bbind:value="area"> # readonly 只读
</div>
<button @click="changeBooks"></button>
</div>
<script>
new Vue({
el: "#app",
data: {
# v-model 双向绑定的值与此处的值同步
length:0,
width:0
},
# 计算属性
computed:{
area:function(){
return this.length*this.width
}}
})
</script>
省市区三级拼接
# get 方法(拼接)/ set方法拆分
<div id = "app">
<div>
<label>省</label>
<input type =text v-model:value="province">
<label>市</label>
<input type =text v-model:value="city">
<label>区</label>
<input type =text v-model:value="dist">
<label>详细地址</label>
<input type =text v-model:value="address">
</div>
</div>
<script>
new Vue({
el: "#app",
data: {
province:"",
city:"",
dist:"",
},
# 计算属性
# 拼接 get 拆分set
computed:{
address:{
get:function(){
# 定义一个变量 result
var result =""
if(this.provice){
result=this.provice+"省"}
if(this.city){
result += this.city+"市"}
if(this.dist){
result += this.dist+"区"}
return result
}
set:function(value){
var result = value.split(/省|市|区/)
if(result&&result.length>0){
this.provice = result[0]}
if(result&&result.length>1){
this.city = result[1]}
if(result&&result.length>2){
this.dict = result[2]}
return result
}
}
}
})
</script>
监听属性
# 针对某个属性进行监听,只要这个值发生了变化 ,就执行相应的函数
<div id = "app">
<label>搜索:</label>
# v-model 双向绑定
<input type ='text' v-model:value="keyword">
<p>结果:</p>
{{answer}}
</div>
<script>
new Vue({
el: "#app",
data: {
# v-model 双向绑定的值与此处的值同步
keyword:"",
anwser:"",
},
# 设置监听
watch:{
keyword:function(newvalue,oldvalue){
this.answer = "加载中..."
# 定时器 setTimeout
setTimeout(() => {
this.answer = "搜索结果:" + newvalue},1000);
};
})
</script>
表单输入绑定
V-model # 实现表单值与属性的双向绑定
"""
v-model 在内部为不同的输入元素使用不同的属性并抛出不同的事件
1、text 和 textarea元素使用value属性和input事件
2、checkbox 和 radio 使用checked 属性和change事件
3、select字段将 value作为prop 并change作为事件
"""
<div id = "app">
<input type ='text' v-model:value="message" placeholder="请输入..">
<p>输入的内容是:{{message}}</p>
<textarea name="" v-model:value="message" cols="30" rows="10"></textarea>
<p>输入的内容是:{{message}}</p>
# checkbox绑定
<input type="checkbox" value="Jack" v-model="checkedNames">
<label for="jack">Jack</label>
<input type="checkbox" value="John" v-model="checkedNames">
<label for="john">John</label>
<input type="checkbox" value="Mike" v-model="checkedNames">
<label for="mike">Mike</label>
<br>
<span>Checked names: {{ checkedNames }}</span>
# radio绑定(单选框)
<input type="radio" value="男" v-model="gender">
<label>男</label>
<br>
<input type="radio" value="女" v-model="gender">
<label>女</label>
<br>
<span>Picked: {{ gender }}</span>
# select下拉框
<select v-model="selected">
# disable 不让选择
<option disabled value="">请选择</option>
# 如果有value值 选择的就是value值
<option value="1">A</option>
<option>B</option>
<option>C</option>
</select>
<span>Selected: {{ selected }}</span>
# 懒加载 lazy ,当光标移出后才显示下面显示的内容
<input type ='text' v-model:value.lazy="message" placeholder="请输入..">
<input type ='text' v-model.lazy="message" placeholder="请输入..">
# 将输入的值转化为数值格式 (值允许输入数字格式)
<input type ='text' v-model.number="age" placeholder="请输入..">
# 过滤用户输入的行首或行尾的空格符 trim
<input type ='text' v-model.trim="msg" placeholder="请输入..">
<p>{{msg}}</p>
</div>
<script>
new Vue({
el: "#app",
data: {
message:"",
checkedNames:[],
gender:"",
select:"",
number:"",
msg:"",
},
})
</script>
自定义组件
# 将可能重复使用的代码封装成组件
<div id = "app">
<button-count></button-count>
<button-count></button-count>
<button-count></button-count>
</div>
<script>
# 自定义组件 button-count(组件名称) 、 template 为内容中要显示的模板
Vue.component('button-count',{
template:'<button @click="count+=1">点击{{count}}次</button>',
data:function(){
return {
count:0
}
}
})
new Vue({
el: "#app",
data: {
message:"",
checkedNames:[],
gender:"",
select:"",
number:"",
msg:"",
},
})
</script>
自定义组件添加属性
<div id = "app">
# 绑定参数
# 此处称为父组件,下面的组件称为子组件
<book-list v-bind:books="books" v-bind:book="book" @check-changed ="checks"></book-list>
</div>
<script>
# 自定义组件 book-list(组件名称) 、 template 为内容中要显示的模板, props 传递参数
# 遵守单一根元素原则
Vue.component('book-list',{
# 传递参数
props:['books'],
# 组件样式
template:'
<div>
<table>
<tr>
<th>序号</th>
<th>标题</th>
</tr>
<tr v-for="(book,index) in books">
<th>{{index+1}}</th>
<th>{{book.title}}</th>
</tr>
</table>'
<sapn>{{book.title}}</sapn>
<input type="checkbook" @click="oncheck">
</div>,
methods:{
oncheck:function(){
# 通知父组件去执行 check-changed 方法
this.$emit('check-changed')
}
}
data:function(){
return {
count:0
}
}
})
new Vue({
el: "#app",
data: {
books:[
{"title":"python","id":1},
{"title":"java","id":2},
{"title":"php","id":3},
],
componentbook : [1,2,3]
}
methods:{
checks:function(){
console.log(123)
}
}
})
</script>
事件传递
<div id = "app">
# 绑定参数
# 此处称为父组件,下面的组件称为子组件
<book-list v-for="book in books" v-bind:book ="book" @check-changed="checks"></book-list>、
</div>
<script>
# 自定义组件 book-list(组件名称) 、 template 为内容中要显示的模板, props 传递参数
# 遵守单一根元素原则
Vue.component('book-list',{
# 传递参数
props:['book'],
# 组件样式
template:'
<div>
<sapn>{{book.title}}</sapn>
<input type="checkbook" @click="oncheck">
</div>,
methods:{
oncheck:function(){
# 通知父组件去执行 check-changed 方法
this.$emit('check-changed',this.book)
}
}
})
new Vue({
el: "#app",
data: {
books:[
{"title":"python","id":1},
{"title":"java","id":2},
{"title":"php","id":3},
],
componentbook : [1,2,3]
}
methods:{
checks:function(book){
# 判断 是否已经有了,如果没有就显示,有了就删除
# indexof 返回元组的下标
var index = this.componentbook.indexof(book)
if(index >= 0){
this.componentbook.splice(index,1)
}else{
this.componentbook.push(book)}
}
}
})
</script>
自定义组件v-model
"""
一个组件上的 v-model 默认会利用名为value的prop(属性)和名为input的事件,但是像单选框,复选框等类型的输入控件可能会将value特性用于不同的目的。
"""
# 点外卖的加减
<div id = "app">
<stepper v-model:value="goods_count"></stepper>
</div>
<script>
# stepper 计步器(计算加减)
Vue.component('stepper',{
# 传递参数
props:['count'],
model:{
# 什么情况触发v-model
event:'count-chaned',
# 传递给v-model的属性
prop:'count'
}
template:'
<div>
<button @click="sub">+</button>
<span>{{count}}<span>
<button @click="add">-</button>
</div>,
methods:{
sub:function(){
this.$emit('count-chaned',this.count-1)
},
add:function(){
this.$emit('count-chaned',this.count+1)
}
}
})
new Vue({
el: "#app",
data: {
goods_count:0
}
})
</script>
插槽
<div id = "app">
# 把 url 传递过来
<nva-link v-bind:url="url">个人中心</nva-link>
<template v-slot:header>header</template>
</div>
<script>
# stepper 计步器(计算加减)
Vue.component('nva-link',{
props:['url'],
template:'
<a v-bind:href="url"></a>
# 插槽
<slot name ="header"></slot>
}
})
new Vue({
el: "#app",
data: {
url:"www.baidu.com"
}
})
</script>
生命周期函数
"""
创建期间函数 :beforeCreate、created、beforeMount、mounted (初始化前、初始化创建)
运行期间函数 :beforUpdate、updated (更新前、更新后)
销毁期间函数 :beforeDestroy、destroyed (销毁前、销毁后)
"""
过滤器的使用
<div>
{{message|capitalize}}
</div>
# 本地过滤(组件中定义)
filters{
capitalize:funciton(value){
if(!value)return''
value = value.toString()
return value.charAt(0).toUpperCase()+value.slice(1)
# return value.replace(" ","") # 替换空格
}
}
# 创建Vue实例之前全局定义过滤器
<script>
Vue.filter('capitalize',function(value){
if(!value)return''
value = value.toString()
return value.charAt(0).toUpperCase()+value.slice(1)
# return value.replace(" ","") # 替换空格
})
new Vue({
el:"#app",
data:{
message:" lcl ",
}
})
</script>
图书管理系统
<div id="app">
<!-- bootstrap中居中样式 -->
<div class="container">
<h1>图书管理系统</h1>
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<label >名称:</label>
<input type="text" class="form-control" v-model="adding_book.name" placeholder="请输入图书名字">
</div>
<div class="form-group">
<label >作者:</label>
<input type="text" class="form-control" v-model="adding_book.author" placeholder="请输入图书作者">
</div>
<div class="form-group">
<label >价格:</label>
<input type="text" class="form-control" v-model="adding_book.price" placeholder="请输入图书价格">
</div>
<div class="form-group">
<label >搜索:</label>
# 通过v-model 定义一个关键字 keywords 通过关键字进行搜索
<input type="text" class="form-control" v-model="keywords" placeholder="请输入搜索内容">
</div>
# 阻止表单跳转
<button type="submit" class="btn btn-default" @click.prevent="add">添加</button>
</form>
<table class="table">
<tr>
<th>序号</th>
<th>名称</th>
<th>价格</th>
<th>时间</th>
<th>操作</th>
</tr>
# book_result 为筛选后的数据集合,从books 演化来的
<tr v-for="(book,index) in book_result">
<td>{{index+1}}</td>
<td>{{book.name}}</td>
<td>{{book.price}}</td>
<td>{{book.atime}}</td>
# 点击后向 del 传递 当前的index参数
<td><button class="btn btn-danger" @click="del(index)">删除</button></td>
</tr>
</table>
</div>
</div>
<script>
new Vue({
el: "#app",
data:{
books:[
{"name":"Python",author:"龟叔",price:89,atime:new Date()},
{"name":"Java",author:"xxx",price:79,atime:new Date()},
],
adding_book:{
name:"",
author:"",
price: 0,
atime:new Date()
},
keywords: ""
},
methods:{
add(){
# JSON.stringify 转成字符串 JSON.parse 转成JS认识的代码
# 此处作用是添加变量后,再次改变输入框中的值,不会因为 v-model的绑定而改变已经添数据的值
var book = JSON.parse(JSON.stringify(this.adding_book))
this.books.push(book)
# 添加完成后 将 添加框中的数据再次变更为 空
this.adding_book={
name:"",
author:"",
price:0,
atime:new Date()}
}
}
# 对数据进行删除,接收index参数
del:function(index){
this.books.splice(index,1)}
# 通过计算属性进行对数据帅选
computed:{
book_result(){
kw = this.keywords
# 判断是否输入关键字
if(this.keywords){
# filter 数组中的过滤方法
# item 为books中的每条数据
# newbooks 接收返回值结果
var newbooks = this.books.filter(function(item){
if(item.name.indexOf(kw)>0){
# 返回当前数据,如果false 则不返回
return true}
else{
return false}
return newbooks})}
else{
return this.books}
}}
Vue路由基本使用
"""
1、使用CDN:
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
2、下载到本地
3、通过npm安装 npm install vue-router
"""
<div id = "app">
# 绑定路由,指向路由
<router-link to="/">首页</router-link>
# 路由匹配到的组件,显示这里
<router-view></router-view>
</div>
<script>
# 定义组件 component 需要加组件的名字,extend没有组件的名字
var index = Vue.extend({template:"<h1>这是首页</h1>"})
# 定义 new VueRouter路由,并用变量 router 进行接收
var router = new VueRouter({
routes:[
{path:"/",component:index} # 加载哪个组件
]
})
new Vue({
el: "#app",
# 定义关键字
router:router
data: {
//
}
</script>
Vue动态路由
<div id = "app">
<router-link to="/">首页</router-link>
<router-link to="/profile/123">个人中心</router-link>
<router-view></router-view>
</div>
<script>
#定义首页模板
var index = Vue.extend({template:"<h1>这是首页</h1>"})
# 动态传递参数,获取参数 userid {{$route.params.userid}}
var profile = Vue.extend({template:"<h1>个人中心{{$route.params.userid}}</h1>"})
# 定义路由匹配
var router = new VueRouter({
routes:[
{path:"/",component:index},
# 带参数 userid
{path:"/profile/:userid",component:profile},
]
})
new Vue({
el: "#app",
# 定义关键字
router:router,
})
</script>
匹配404错误
"""
在路由规则中,* 代表任意字符,所以在路由最后添加* 路由,没有匹配到视图的都会导入到这个URL中
"""
<script>
#定义首页模板
var index = Vue.extend({template:"<h1>这是首页</h1>"})
# 动态传递参数,获取参数 userid {{$route.params.userid}}
var profile = Vue.extend({template:"<h1>个人中心{{$route.params.userid}}</h1>",
mounted(){
if(this.$route.params.userid!='123'){
this.$router.replace('/404')}}})
#定义notfind 404 模板
var notfind = Vue.extend({template:"<p>你要找的页面没找到 404 </p>"})
# 定义路由匹配
var router = new VueRouter({
routes:[
{path:"/",component:index},
{path:"/profile/:userid",component:profile},
{path:"*",component:notfind},
{path:"/404",component:notfind},
]
})
new Vue({
el: "#app",
router:router,
})
</script>
嵌套路由
<script>
#定义首页模板
var index = Vue.extend({template:"<h1>这是首页</h1>"})
# 动态传递参数,获取参数 userid {{$route.params.userid}}
var user = Vue.extend({template:
<div>
'<h1>个人中心{{$route.params.userid}}</h1>
<ul class="nav nav-tabs">
<li role="presentation" class="active">
<router-link to="/user/123/setting">设置</router-link>
</li>
<li role="presentation">
<router-link to="/user/123/message">消息</router-link>
</li>
</ul>
# 定义子标签的显示位置
<div class="container">
<router-view></router-view>
</div>
</div>
'
})
var setting = Vue.extend({template:"<h1>设置</h1>"})
var router = new VueRouter({
routes:[
{path:"/",component:index},
# 嵌套路由写法
{
path:"/user/:userid",
component:user,
children:[
{path:"",component:setting},
{path:"setting",component:setting},
{path:"message",component:message},
]
},
{path:"*",component:notfind},
{path:"/404",component:notfind},
]
})
new Vue({
el: "#app",
router:router,
})
</script>
编程式导航 $router.push
<div id = "app">
<button @click="gotoPost">列表</button>
<button @click="gotoProfile">个人中心</button>
<button @click="login">登陆</button>
<button @click="gonext">下一步</button>
<button @click="goprev">上一步</button>
# 程序显示出口
<router-view></router-view>
</div>
<script>
# 动态传递参数,获取参数 userid {{$route.params.userid}}
var post = Vue.extend({template:"<h1>列表</h1>"})
var profile = Vue.extend({template:"<h1>个人中心{{$route.params.userid}}</h1>"}
var router = new VueRouter({
routes:[
{path:"/post",component:post},
{path:"/profile/:userid",component:profile,name :"myprofile"},
]
})
new Vue({
el: "#app",
router:router,
methods:{
# 通过次方法进行跳转到 /post 路由界面
gotoPost:function(){
this.$router.push("/post")},
gotoProfile(){
this.$router.push(name:"myprofile",params:{userid:123})},
login(){
this.$router.push({path:"login",query:{wd:"python"}})}
gonext(){
this.$router.go(1)},
goprev(){
this.$router.go(-1)},
}
})
</script>
命名路由
<div id = "app">
# 通过命名方式寻找路由,注意冒号
<router-link :to="{name:'index'}">首页</router-link>
<router-link to="/profile/123">个人中心</router-link>
<router-view></router-view>
</div>
<script>
#定义首页模板
var index = Vue.extend({template:"<h1>这是首页</h1>"})
var router = new VueRouter({
routes:[
{path:"/",name:"index",component:index},
]
})
new Vue({
el: "#app",
router:router,
})
</script>
命名视图
<div id = "app">
<div class="header">
<router-view name="header"></router-view>
</div>
<div class="body">
<router-view name="left"></router-view>
<router-view name="right"></router-view>
</div>
<div class="footer">
<router-view name="footer"></router-view>
</div>
</div>
<script>
#定义首页模板
var headerc = Vue.extend({template:"<h1>header部分</h1>"})
var leftc = Vue.extend({template:"<h1>leftr部分</h1>"})
var rightc = Vue.extend({template:"<h1>right部分</h1>"})
var footerc = Vue.extend({template:"<h1>footer部分</h1>"})
var router = new VueRouter({
routes:[
{path:"/",component:{
header:headerc,
left:leftc,
right:rightc,
footer:footerc,
}
]
})
new Vue({
el: "#app",
router:router,
})
</script>
重定向和别名
<div id = "app">
<div class="header">
<router-view></router-view>
</div>
</div>
<script>
#定义首页模板
var article = Vue.extend({template:"<h1>这是article</h1>"})
var router = new VueRouter({
routes:[
# redirect 重定向
{path:"/",redirect:"/article"},
# 别名 alist:
{path:"/article",component:article,alias:"/list"},
]
})
new Vue({
el: "#app",
router:router,
})
</script>