一、引入
开发环境:<script src="https://cdn.jsdelivr.net/npm/vue">script>
生产环境:<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js">script>
二、基本使用
1、声明式渲染 <div id=app> {{msg}} div> Vue{ el:"#app", data:{ msg:"Hello Vue" } } Hello Vue <div id="app-2"> <span v-bind:title="message"> 鼠标悬停几秒钟查看此处动态绑定的提示信息! span> div> var app2 = new Vue({ el: '#app-2', data: { message: '页面加载于 ' + new Date().toLocaleString() } }) 鼠标悬停几秒钟查看此处动态绑定的提示信息! 2、条件与循环 <div id="app-3"> <p v-if="seen">现在你看到我了p> div> var app3 = new Vue({ el: '#app-3', data: { seen: true } }) 现在你看到我了 <div id="app-4"> <ol> <li v-for="todo in todos"> {{ todo.text }} li> ol> div> var app4 = new Vue({ el: '#app-4', data: { todos: [ { text: '学习 JavaScript' }, { text: '学习 Vue' }, { text: '整个牛项目' } ] } }) 3、处理用户输入 <div id="app-5"> <p>{{ message }}p> <button v-on:click="reverseMessage">反转消息button> div> var app5 = new Vue({ el: '#app-5', data: { message: 'Hello Vue.js!' }, methods: { reverseMessage: function () { this.message = this.message.split('').reverse().join('') } } })
三、局部组件(先声明子组件、再挂载子组件、再使用子组件)
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
<style>
* {
margin: 0;
padding: 0;
}
.main{
width: 100%;
}
.header {
height: 50px;
background-color: aqua;
}
.left{
height: 800px;
width: 30%;
background-color: aquamarine;
float: left;
}
.right{
height: 800px;
width: 70%;
background-color: antiquewhite;
float: right;
}
style>
head>
<body>
<div id="app">
div>
<script>
//声明头部组件
var Vheader={
template:`
<div class="header" >头部</div>
`,
};
//声明左侧栏组件
var Vleft={
template:`
<div class="left">左边栏</div>
`
};
//声明右侧栏组件
var Vright={
template:`
<div class="right">右边栏</div>
`,
};
//声明入口组件
var Vmain={
//使用组件
template:`
<div class="main" >
<Vheader></Vheader>
<Vleft></Vleft>
<Vright></Vright>
</div>
`,
//挂载组件
components:{
Vheader,
Vleft,
Vright,
}
};
new Vue({
el:"#app",
components:{
Vmain,
},
template: ' '
})
script>
body>
html>
四、父组件向子组件传数据(通过props)
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
<style>
* {
margin: 0;
padding: 0;
}
.main{
width: 100%;
}
.header {
height: 50px;
background-color: aqua;
}
.left{
height: 800px;
width: 30%;
background-color: aquamarine;
float: left;
}
.right{
height: 800px;
width: 70%;
background-color: antiquewhite;
float: right;
}
style>
head>
<body>
<div id="app">
div>
<script>
//声明头部组件
var Vheader={
template:`
<div class="header" >{{header}}</div>
`,
props:["header",]
};
//声明左侧栏组件
var Vleft={
template:`
<div class="left">{{left}}</div>
`,
props: ["left",]
};
//声明右侧栏组件
var Vright={
template:`
<div class="right">{{right}}</div>
`,
props:["right",]
};
//声明入口组件
var Vmain={
//使用组件
template:`
<div class="main" >
<Vheader v-bind:header="content.header"></Vheader>
<Vleft v-bind:left="content.left"></Vleft>
<Vright v-bind:right="content.right"></Vright>
</div>
`,
//挂载组件
components:{
Vheader,
Vleft,
Vright,
},
props: ["content",]
};
new Vue({
el:"#app",
components:{
Vmain,
},
template: ' ',
data:{
content:{
header:"头部区",
left:"左侧区",
right:"右侧区"
}
}
})
script>
body>
html>
五、子组件通过事件向父组件传递数据($emit)
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
<style>
* {
margin: 0;
padding: 0;
}
.header {
height: 50px;
background-color: aqua;
}
.left{
height: 800px;
width: 30%;
background-color: aquamarine;
float: left;
}
.right{
height: 800px;
width: 70%;
background-color: antiquewhite;
float: right;
}
style>
head>
<body>
<div id="app">
div>
<script>
//声明头部组件
var Vheader={
template:`
<div class="header" >头部</div>
`,
};
//声明左侧栏组件
var Vleft={
template:`
<div class="left">左边栏</div>
`
};
//声明右侧栏组件
var Vright={
template:`
<div class="right">
<div>这是内容</div>
<button v-on:click="enlargetext">
将页面字体放大
</button>
</div>
`,
methods:{
enlargetext:function () {
console.log("执行enlargetext方法");
//触发事件
this.$emit('enlarge-text',5)
}
}
};
//声明入口组件
var Vmain={
//使用组件
template:`
<div class="main" v-bind:style="{ fontSize: postFontSize + 'px' }" >
<Vheader></Vheader>
<Vleft></Vleft>
<Vright v-on:enlarge-text="onEnlargeText"></Vright>
</div>
`,
//注册组件
components:{
Vheader,
Vleft,
Vright,
},
data: function () {
return{
postFontSize: 28
}
},
methods: {
//定义onEnlargeText方法
onEnlargeText: function (enlargeAmount) {
this.postFontSize += enlargeAmount
},
}
};
new Vue({
el:"#app",
components:{
Vmain,
},
template: ' '
})
script>
body>
html>
六、全局组件的使用(Vue.component("Name",{}),先声明,再使用)
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
<style>
* {
margin: 0;
padding: 0;
}
.main{
width: 100%;
}
.header {
height: 50px;
background-color: aqua;
}
.left{
height: 800px;
width: 30%;
background-color: aquamarine;
float: left;
}
.right{
height: 800px;
width: 70%;
background-color: antiquewhite;
float: right;
}
style>
head>
<body>
<div id="app">
div>
<script>
//声明全局组件,第一个参数:全局组件名称,第二个参数(和局部组件类似):options
Vue.component("Btn-btn",{
template:`<button>btn</button>`
});
//声明头部组件
var Vheader={
template:`
<div class="header" >头部</div>
`,
};
//声明左侧栏组件
var Vleft={
template:`
<div class="left">左边栏</div>
`
};
//声明右侧栏组件,使用全局组件
var Vright={
template:`
<div class="right">
<p>右边栏</p>
<Btn-btn></Btn-btn>
<Btn-btn></Btn-btn>
<Btn-btn></Btn-btn>
</div>
`,
};
//声明入口组件
var Vmain={
//使用组件
template:`
<div class="main" >
<Vheader></Vheader>
<Vleft></Vleft>
<Vright></Vright>
</div>
`,
//挂载组件
components:{
Vheader,
Vleft,
Vright,
}
};
new Vue({
el:"#app",
components:{
Vmain,
},
template: ' '
})
script>
body>
html>
七、插槽slot及element-ui使用
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<script src="https://unpkg.com/element-ui/lib/index.js">script>
<style>
* {
margin: 0;
padding: 0;
}
.main{
width: 100%;
}
.header {
height: 50px;
background-color: aqua;
}
.left{
height: 800px;
width: 30%;
background-color: aquamarine;
float: left;
}
.right{
height: 800px;
width: 70%;
background-color: antiquewhite;
float: right;
}
style>
head>
<body>
<div id="app">
div>
<script>
//声明全局组件,第一个参数:全局组件名称,第二个参数(和局部组件类似):options
Vue.component("Btn-btn",{
template:`<el-button v-bind:type="type"><slot></slot></el-button>`,
props:['type',]
});
//声明头部组件
var Vheader={
template:`
<div class="header" >头部</div>
`,
};
//声明左侧栏组件
var Vleft={
template:`
<div class="left">左边栏</div>
`
};
//声明右侧栏组件,使用全局组件
var Vright={
template:`
<div class="right">
<p>右边栏</p>
<Btn-btn v-bind:type="primary">登录</Btn-btn>
<Btn-btn v-bind:type="success">注册</Btn-btn>
<Btn-btn v-bind:type="danger">退出</Btn-btn>
</div>
`,
//注意,组件中的data一定要是函数,而且要有返回值
data:function(){
return{
primary:"primary",
success:"success",
danger:"danger",
}
}
};
//声明入口组件
var Vmain={
//使用组件
template:`
<div class="main" >
<Vheader></Vheader>
<Vleft></Vleft>
<Vright></Vright>
</div>
`,
//挂载组件
components:{
Vheader,
Vleft,
Vright,
}
};
new Vue({
el:"#app",
components:{
Vmain,
},
template: ' '
})
script>
body>
html>
八、全局过滤器和局部过滤器
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
head>
<body>
<div id="app">
<input type="text" v-model="price">
<div>{{price | newPrice}}div>
<div>{{msg | reverseCode}}div>
div>
<script>
//注册全局过滤器,第一个参数为全局过滤器名称,第二个参数为函数
Vue.filter("reverseCode",
function(value){
return value.split("").reverse().join("")
}
);
new Vue({
el:"#app",
data:{
price:0,
msg:"Hello Vue!"
},
//注册局部过滤器
filters:{
newPrice:function (value) {
return "$"+value
}
}
})
script>
body>
html>
九、侦听器watch
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
head>
<body>
<div id="app">
<input type="text" v-model="firstName">
<input type="text" v-model="lastName">
<div>{{fullName}}div>
div>
<script>
new Vue({
el:"#app",
data:function(){
return {
firstName:"hou",
lastName:"gang",
fullName:"hou gang",
}
},
watch:{
firstName: function (value) {
this.fullName = value +" "+ this.lastName
},
lastName: function (value) {
this.fullName = this.firstName +" "+ value
}
}
})
script>
body>
html>
十、计算属性computed
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
head>
<body>
<div id="app">
<input type="text" v-model="firstName">
<input type="text" v-model="lastName">
<div>{{fullName}}div>
div>
<script>
new Vue({
el:"#app",
data:function(){
return {
firstName:"hou",
lastName:"gang",
// fullName:"hou gang",
}
},
//侦听器
// watch:{
// firstName: function (value) {
// this.fullName = value +" "+ this.lastName
// },
// lastName: function (value) {
// this.fullName = this.firstName +" "+ value
// }N
// },
//计算属性
computed:{
fullName:function () {
return this.firstName + ' ' + this.lastName
}
}
})
script>
body>
html>
十一、音乐播放器案例
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
<style>
.active{
color: red;
background-color: aquamarine;
}
style>
head>
<body>
<div id="app">
<audio v-bind:src="mp3s[checkIndex].src" controls autoplay>audio>
<li v-for="mp3 in mp3s" v-on:click="checkMp3(mp3.index)" :class="{active:checkIndex===mp3.index}">
{{mp3.title}}
li>
div>
<script>
//1、音乐数据结构
MP3=[
{
index:0,
title:"李春波-小芳",
src:"./mp3/李春波 - 小芳.mp3"
},
{
index:1,
title:"林志颖 - 稻草人",
src:"./mp3/林志颖 - 稻草人.mp3"
},
{
index:2,
title:"陈百强 - 偏偏喜欢你",
src:"./mp3/陈百强 - 偏偏喜欢你.mp3"
},
{
index:3,
title:"齐秦 - 我拿什么爱你",
src:"./mp3/齐秦 - 我拿什么爱你.mp3"
},
];
new Vue({
el:"#app",
data:function(){
return {
//2、定义歌曲变量,传递给前端循环获取歌曲使用
mp3s:MP3,
startIndex:0
}
},
methods:{
checkMp3:function (index) {
this.startIndex = index
}
},
computed:{
checkIndex:function () {
return this.startIndex
}
}
})
script>
body>
html>
十二、组件生命周期钩子
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
head>
<body>
<div id="app">
div>
<script>
var Test={
template: `<div>AAA</div>`,
data:function(){
return{
msg:"MSG"
}
},
//在实例初始化之后,数据观测 (data observer) 和 event/watcher 事件配置之前被调用。
beforeCreate:function () {
console.log("beforeCreate"+" "+this.msg)
},
//在实例创建完成后被立即调用。在这一步,实例已完成以下的配置:数据观测 (data observer),属性和方法的运算,watch/event 事件回调。然而,挂载阶段还没开始,$el 属性目前不可见。
created:function () {
console.log("created"+" " +this.msg)
},
//在挂载开始之前被调用:相关的 render 函数首次被调用。
beforeMount:function () {
},
//el 被新创建的 vm.$el 替换,并挂载到实例上去之后调用该钩子。如果 root 实例挂载了一个文档内元素,当 mounted 被调用时 vm.$el 也在文档内。
mounted:function () {
},
//数据更新时调用,发生在虚拟 DOM 打补丁之前。这里适合在更新之前访问现有的 DOM,比如手动移除已添加的事件监听器。
beforeUpdate:function () {
},
//由于数据更改导致的虚拟 DOM 重新渲染和打补丁,在这之后会调用该钩子。
updated:function () {
},
//keep-alive 组件激活时调用。
activated:function () {
},
//keep-alive 组件停用时调用。
deactivated:function () {
},
//实例销毁之前调用。在这一步,实例仍然完全可用。
beforeDestroy:function () {
},
//Vue 实例销毁后调用。调用后,Vue 实例指示的所有东西都会解绑定,所有的事件监听器会被移除,所有的子实例也会被销毁。
destroyed:function () {
},
//当捕获一个来自子孙组件的错误时被调用。此钩子会收到三个参数:错误对象、发生错误的组件实例以及一个包含错误来源信息的字符串。此钩子可以返回 false 以阻止该错误继续向上传播。
errorCaptured:function () {
},
};
new Vue({
el:"#app",
template:" ",
components:{
Test,
}
})
script>
body>
html>
十三、$refs&nextTick
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
head>
<body>
<div id="app">
div>
<script>
var Test={
template: `<div>
<p ref="test" v-if="isShow">哈哈哈哈哈</p>
<p>{{isShow}}</p>
<button @click="isShowFunc">点我</button>
</div>`,
data:function(){
return{
isShow:false
}
},
//el 被新创建的 vm.$el 替换,并挂载到实例上去之后调用该钩子。如果 root 实例挂载了一个文档内元素,当 mounted 被调用时 vm.$el 也在文档内。
mounted:function () {
//this.$refs.test只有在mounted后才生效
console.log(this);//显示this对像
},
methods:{
isShowFunc:function (event) {
//console.log("isShow执行了");
this.isShow = !this.isShow;
this.$nextTick(function () {
console.log(this.$refs.test.innerText)
});
}
}
};
new Vue({
el:"#app",
template:" ",
components:{
Test,
}
})
script>
body>
html>
十四、vue-router基本用法
示例一:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="https://unpkg.com/vue/dist/vue.js">script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js">script>
head>
<body>
<div id="app">
<h1>Hello App!h1>
<p>
<router-link to="/foo">Go to Foorouter-link>
<router-link to="/bar">Go to Barrouter-link>
p>
<router-view>router-view>
div>
<script>
// 0. 如果使用模块化机制编程,导入Vue和VueRouter,要调用 Vue.use(VueRouter)
// 1. 定义 (路由) 组件。
// 可以从其他文件 import 进来
const Foo = { template: 'foo' };
const Bar = { template: 'bar' };
// 2. 定义路由
// 每个路由应该映射一个组件。 其中"component" 可以是
// 通过 Vue.extend() 创建的组件构造器,
// 或者,只是一个组件配置对象。
// 我们晚点再讨论嵌套路由。
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
];
// 3. 创建 router 实例,然后传 `routes` 配置
// 你还可以传别的配置参数, 不过先这么简单着吧。
const router = new VueRouter({
routes // (缩写) 相当于 routes: routes
});
// 4. 创建和挂载根实例。
// 记得要通过 router 配置参数注入路由,
// 从而让整个应用都有路由功能
const app = new Vue({
router
}).$mount('#app')
// 现在,应用已经启动了!
script>
body>
html>
示例二:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="vue.js">script>
<script src="vue-router.js">script>
head>
<body>
<div id="app">
div>
<script>
Vue.use(VueRouter);
var Login={
template:`<div>登录页面</div>`
};
var Register={
template: `<div>注册页面</div>`
};
var router=new VueRouter({
routes: [
{
path:'/login',
name:"login",
component:Login
},
{
path:'/register',
name:"register",
component:Register
}
]
});
var App={
template:`
<div>
<h1>Hello App!</h1>
<p>
<router-link to="/login">登录</router-link>
<router-link to="/register">注册</router-link>
<router-link :to="{name:'login'}">登录</router-link>
<router-link :to="{name:'register'}">注册</router-link>
</p>
<router-view></router-view>
</div>
`
};
new Vue({
el:"#app",
components:{
App
},
router,
template:" ",
})
script>
body>
html>
十五、params与query参数
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="https://unpkg.com/vue/dist/vue.js">script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js">script>
head>
<body>
<div id="app">
div>
<script>
Vue.use(VueRouter);
var UseParams={
template:`<div>我是用户1</div>`,
created(){
console.log(this.$route);
console.log(this.$router);
console.log(this.$route.params.userId);
}
};
var UseQuery={
template: `<div>我是用户2</div>`,
created(){
console.log(this.$route);
console.log(this.$router);
console.log(this.$route.query.userId);
}
};
var router=new VueRouter({
routes: [
{
path:'/user/:userId',
name:"usep",
component:UseParams
},
{
path:'/user',
name:"useq",
component:UseQuery
}
]
});
var App={
template:`
<div>
<h1>Hello App!</h1>
<p>
<router-link :to="{name:'usep',params:{userId:1}}">用户1</router-link>
<router-link :to="{name:'useq',query:{userId:2}}">用户2</router-link>
</p>
<router-view></router-view>
</div>
`
};
new Vue({
el:"#app",
components:{
App
},
router,
template:" ",
})
script>
body>
html>
十六、编程式导航
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="https://unpkg.com/vue/dist/vue.js">script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js">script>
head>
<body>
<div id="app">
div>
<script>
Vue.use(VueRouter);
var UseParams={
template:`<div>我是用户1</div>`,
created(){
console.log(this.$route);
console.log(this.$router);
console.log(this.$route.params.userId);
}
};
var UseQuery={
template: `<div>我是用户2</div>`,
created(){
console.log(this.$route);
console.log(this.$router);
console.log(this.$route.query.userId);
}
};
var router=new VueRouter({
routes: [
{
path:'/user/:userId',
name:"usep",
component:UseParams
},
{
path:'/user',
name:"useq",
component:UseQuery
}
]
});
var App={
template:`
<div>
<h1>Hello App!</h1>
<p>
<button @click="usepHandle">用户1</button>
<button @click="useqHandle">用户2</button>
<router-link :to="{name:'usep',params:{userId:1}}">用户1</router-link>
<router-link :to="{name:'useq',query:{userId:2}}">用户2</router-link>
</p>
<router-view></router-view>
</div>
`,
methods:{
usepHandle:function () {
this.$router.push({name:'usep',params:{userId:123}})
},
useqHandle:function () {
this.$router.push({name:'useq',query:{userId:123}})
},
}
};
new Vue({
el:"#app",
components:{
App
},
router,
template:" ",
})
script>
body>
html>
十七、㠌套路由
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="https://unpkg.com/vue/dist/vue.js">script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js">script>
head>
<body>
<div id="app">
div>
<script>
Vue.use(VueRouter);
var Home={
template:`<div>
<router-link to="/home/music">音乐</router-link>
<router-link to="/home/movie">电影</router-link>
<router-view></router-view>
</div>`,
};
var Music={
template:`<div>我是音乐</div>`
};
var Movie={
template:`<div>我是电影</div>`
};
var router=new VueRouter({
routes: [
{
path:'',
//url为‘/’
// component:Home,
//url为‘/home’
redirect:'/home'
},
{
path:'/home',
//有子路由的时候父路由不能有name,不然会有警告
// name:"home",
component:Home,
children:[
{
path:'',
component:Music
},
{
path:'music',
name:"music",
component: Music
},
{
path:'movie',
name:"movie",
component: Movie
}
]
}
]
});
var App={
template:`
<div>
<router-link to="/home">首页</router-link>
<router-view></router-view>
</div>
`
};
new Vue({
el:"#app",
components:{
App
},
router,
template:" ",
})
script>
body>
html>
十八、动态路由匹配
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="https://unpkg.com/vue/dist/vue.js">script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js">script>
head>
<body>
<div id="app">
div>
<script>
Vue.use(VueRouter);
var Home={
template:`<div>
<router-link :to="{name:'comment',params:{title:'music'}}">音乐</router-link>
<router-link :to="{name:'comment',params:{title:'movie'}}">电影</router-link>
<router-view></router-view>
</div>`,
};
var Comment={
template:`<div>我是{{msg}}</div>`,
data:function(){
return {
msg:'music'
}
},
watch:{
$route:function (to,from) {
console.log(to);
console.log(from);
this.msg=to.params.title
}
}
};
var router=new VueRouter({
routes: [
{
path:'',
//url为‘/’
// component:Home,
//url为‘/home’
redirect:'/home'
},
{
path:'/home',
//有子路由的时候父路由不能有name,不然会有警告
// name:"home",
component:Home,
children:[
{
path:'',
component:Comment
},
{
path:'comment/:title',
name:"comment",
component: Comment
},
]
}
]
});
var App={
template:`
<div>
<router-link to="/home">首页</router-link>
<router-view></router-view>
</div>
`
};
new Vue({
el:"#app",
components:{
App
},
router,
template:" ",
})
script>
body>
html>
十九、keep-alive在路由中的使用
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="https://unpkg.com/vue/dist/vue.js">script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js">script>
head>
<body>
<div id="app">
div>
<script>
Vue.use(VueRouter);
var Music={
template:`<div>
音乐
</div>`,
created(){
console.log("music created")
},
mounted(){
console.log("music mounted")
},
destroyed(){
console.log("music destroyed")
}
};
var Movie={
template:`<div @click="changeColor">
电影
</div>`,
created(){
console.log("movie created")
},
mounted(){
console.log("movie mounted")
},
destroyed(){
console.log("movie destroyed")
},
methods:{
//字体变红
changeColor(event){
event.target.style.color='red'
}
}
};
var router=new VueRouter({
routes: [
{
path:'/music',
name:'music',
component:Music
},
{
path:'/movie',
name:'movie',
component:Movie
}
]
});
//keep-alive可以保持组件,不反复创建和销毁,节省资源
var App={
template:`
<div>
<router-link :to="{name:'music'}">音乐</router-link>
<router-link :to="{name:'movie'}">电影</router-link>
<keep-alive>
<router-view></router-view>
</keep-alive>
</div>
`
};
new Vue({
el:"#app",
components:{
App
},
router,
template:" ",
})
script>
body>
html>
二十、权限控制
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="https://unpkg.com/vue/dist/vue.js">script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js">script>
head>
<body>
<div id="app">
div>
<script>
Vue.use(VueRouter);
var Home={
template:`<div>
首页
</div>`,
};
var Login={
template:`<div>
<input type="text" v-model="name">
<input type="password" v-model="pwd">
<input type="button" value="登录" @click="loginHandler">
</div>`,
data:function(){
return {
name:'',
pwd:''
}
},
methods:{
loginHandler(){
console.log("点击了登录按钮");
localStorage.setItem("user",{name:this.name,pwd:this.pwd});
this.$router.push({name:'questionBank'})
}
}
};
var QuestionBank={
template:`<div>
题库
</div>`,
};
var Logout={
template:`<div>
<a href="#" @click="clear">退出</a>
</div>`,
methods: {
clear(){
localStorage.clear("user")
}
}
};
var router=new VueRouter({
routes: [
{
path:'/home',
name:'home',
component:Home
},
{
path:'/questionBank',
name:'questionBank',
component:QuestionBank,
meta:{
auth:true
}
},
{
path:'/login',
name:'login',
component:Login
},
{
path:'/logout',
name:'logout',
component:Logout
},
]
});
router.beforeEach(function (to,from,next) {
console.log(to);
console.log(from);
console.log(localStorage.getItem("user"));
if (to.meta.auth){
if(localStorage.getItem("user")){
next()
}else{
next({
path:'/login'
})
}
}else{
next()
}
});
//keep-alive可以保持组件,不反复创建和销毁,节省资源
var App={
template:`
<div>
<router-link :to="{name:'home'}">首页</router-link>
<router-link :to="{name:'questionBank'}">题库</router-link>
<router-link :to="{name:'login'}">登录</router-link>
<router-link :to="{name:'logout'}" >退出</router-link>
<keep-alive>
<router-view></router-view>
</keep-alive>
</div>
`
};
new Vue({
el:"#app",
components:{
App
},
router,
template:" ",
})
script>
body>
html>