vue2
Vue2
1 vue 核心
1.1 环境搭建
引入工具
引入开发者工具 vue devtools
关闭相关提示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>introduce vue</title>
<!-- 引入Vue -->
<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<script type="text/javascript">
Vue.config.productionTip = false //阻止vue 在启动时生成生产提示
</script>
</body>
</html>
案例
官网vue2下载
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>introduce vue</title>
<!-- 引入Vue -->
<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<!--
初识vue:
1.想让Vue工作,就必须创建一个Vue实例,且要传入一个配置对象;
2.root容器里的代码依然符合html规范,只不过混入了一些特殊的Vue语法;
3.root容器里的代码被称为【vue模板】
-->
<!-- 准备好一个容器 -->
<div id="root">
<h1>Hello,{{name}}</h1>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止vue 在启动时生成生产提示
//创建Vue实例
new Vue({
el: '#root', //el:element 用于指定当前Vue实例为哪个容器服务,值通常为css选择器字符串
data: { //data中用于存储数据,数据供el所指定的容器去使用,值我们暂时先写成一个对象。
name: '千夜'
}
})
</script>
</body>
</html>
运行结果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>introduce vue</title>
<!-- 引入Vue -->
<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<!--
初识vue:
1.想让Vue工作,就必须创建一个Vue实例,且要传入一个配置对象;
2.root容器里的代码依然符合html规范,只不过混入了一些特殊的Vue语法;
3.root容器里的代码被称为【vue模板】
4.Vue实例和容器是一一对应的;
5.真实开发中只有一个Vue实例,并且会配合着组件一起使用;
6.{{xxx}}中的xxx要写js表达式,且xxx可以自动读取到data中的所有属性;
7.一旦data中的数据发生改变,那么页面中用到该数据的地方也会自动更新;
注意区分:js表达式 和 js代码(语句)
1.表达式:一个表达式会产生一个值,可以放在任何一个需要值的地方:
1)a
2) a+b
3) demo(1)
4) x===y ? 'a' : 'b'
2.js代码(语句)
1)if(){}
2) for(){}
-->
<!-- 准备好一个容器 -->
<div id="root">
<h1>Hello,{{name.toUpperCase()}}, {{address}}, {{Date.now()}}</h1>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止vue 在启动时生成生产提示
//创建Vue实例
new Vue({
el: '#root', //el:element 用于指定当前Vue实例为哪个容器服务,值通常为css选择器字符串
data: { //data中用于存储数据,数据供el所指定的容器去使用,值我们暂时先写成一个对象。
name: 'fengpeng',
address: '成都',
}
})
</script>
</body>
</html>
运行结果
1.2 模板语法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<!--
Vue模板语法有2大类:
1.插值语法:
功能:用于解析标签体内容。
写法:{{xxx}},xxx是js表达式,且可以直接读取到data中的所有属性。
2.指令语法
功能:用于解析标签(包括:标签属性、标签体内容、绑定事件.....)。
举例: v-bind:href="xxx" 或 简写为 :href="xxx",xxx同样要写js表达式,
且可以直接读取到data中的所有属性。
备注: Vue中有很多的指令,且形式都是:v-????,此处我们只是拿v-bind举个例子。
-->
<!-- 准备好一个容器 -->
<div id="root">
<h1>插值语法</h1>
<h3>你好,{{name}}</h3>
<hr/>
<h1>指令语法</h1>
<a v-bind:href="school.url" v-bind:x="hello">点我去{{school.name}}1</a>
<a :href="school.url.toUpperCase()" :x="hello">点我去{{school.name}}2</a>
</div>
<script type="text/javascript">
Vue.config.productionTip = false
new Vue({
el: '#root',
data: {
name: 'feng',
school: {
url: 'https://www.baidu.com',
name: '百度'
}
}
})
</script>
</body>
</html>
运行结果
1.3 数据绑定
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<!--
Vue中有2种数据绑定的方式:
1.单向绑定(v-bind):数据只能从data流向页面。
2.双向绑定(v-model):数据不仅能从data流向页面,还可以从页面流向data
备注:
1.双向绑定一般都应用在表单类元素上(如: input、select等)
2.v-model:value可以简写为v-model,因为v-model默认收集的就是value值。
-->
<!-- 准备好一个容器 -->
<div id="root">
<!-- 普通写法 -->
<!-- 单向数据绑定: <input type="text" v-bind:value="name"><br>
双向数据绑定: <input type="text" v-model:value="name"> -->
<!-- 简写 -->
单向数据绑定: <input type="text" :value="name"><br>
双向数据绑定: <input type="text" v-model="name">
<!-- 如下代码是错误的,因为v-model只能应用在表单类元素(输入类元素上) -->
<!-- <h2 v-model:x="name">你好呀</h2> -->
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
new Vue({
el: '#root',
data: {
name: 'feng'
}
})
</script>
</body>
</html>
运行结果
1.4 el和data两种写法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<!--
data与el的2种写法
1.el有2种写法
(1).new Vue时候配置el属性。
(2).先创建Vue实例,随后再通过vm.$mount('#root')指定el的值。
2.data有2种写法
(1).对象式
(2).函数式
如何选择:目前哪种写法都可以,以后学习到组件时,data必须使用函数式,否则会报错。
3.一个重要的原则:
由vue管理的函数,一定不要写箭头函数,一旦写了箭头函数,this就不再是Vue实例了。
-->
<!-- 准备好一个容器 -->
<div id="root">
<h1>hello,{{name}}</h1>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
/* const v = new Vue({
// el: '#root', //第一种写法
data: {
name: 'feng'
}
})
v.$mount('#root') //第二种写法 */
new Vue({
el: '#root',
//data的第一种写法:对象式
/*data: {
name: 'feng'
} */
//data的第二种写法:函数式
/* data:function(){
console.log('@@@',this) //此处的this是Vue实例对象
return {
name: 'feng'
}
} */
//第二种方法函数式可以简写
data(){
console.log('@@@',this) //此处的this是Vue实例对象
return {
name: 'feng'
}
}
})
</script>
</body>
</html>
1.5 MVVM
<body>
<!--
MVVM模型
1.M:模型(Model) : data中的数据
2.V:视图(View):模板代码
3.VM:视图模型(ViewModel): Vue实例
观察发现:
1.data中所有的属性,最后都出现在了vm身上。
2.vm身上所有的属性 及 Vue原型上所有属性,在Vue模板中都可以直接使用。
-->
<!-- 准备好一个容器 -->
<div id="root">
<h1>学校名称: {{name}}</h1>
<h1>学校地址: {{address}}</h1>
<h1>测试一下1: {{$options}}</h1>
<h1>测试一下2: {{$emit}}</h1>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
const mv = new Vue({
el: '#root',
data: {
name: '大学',
address: '成都'
}
})
console.log(mv)
</script>
</body>
运行结果
1.6 数据代理
Object.defineProperty
<body>
<script type="text/javascript">
let number = 18
let person = {
name: 'feng',
sex: 'nan',
}
Object.defineProperty(person,'age',{
// value: 18,
// enumerable: true, //控制属性是否可以枚举,默认值是false
// writable: true, //控制属性是否可以被修改,默认值是false
// configurable: true, //控制属性是否可以被删除,默认值是false
//当有人读取person的age属性时,get函数(getter)就会被调用,且返回值就是age的值
get(){
console.log('有人读取age属性了')
return number
},
//当有人修改person的age属性时,set函数(setter)就会被调用,且会收到修改的具体值
set(value){
console.log('有人修改了age属性,且值是'+value)
}
})
// console.log(Object.keys(person)) //将对象的所有key转成数组
</script>
</body>
理解
<body>
<!-- 准备好一个容器 -->
<div id="root">
</div>
<!-- 数据代理:通过一个对象代理对另一个对象中属性的操作(读/写) -->
<script type="text/javascript">
let obj = {x: 100}
let obj2 = {y: 200}
Object.defineProperty(obj2,'x',{
get(){
return obj.x
},
set(value){
obj.x = value
}
})
</script>
</body>
运行结果
Vue中数据代理
<body>
<!--
1.Vue中的数据代理:
通过vm对象来代理data对象中属性的操作(读/写)
2.Vue中数据代理的好处:
更加方便的操作data中的数据
3.基本原理:
通过object.defineProperty()把data对象中所有属性添加到vm上.
为每一个添加到vm上的属性,都指定一个getter/setter。
在getter/setter内部去操作(读/写)data中对应的属性。
-->
<!-- 准备好一个容器 -->
<div id="root">
<h2>学校名称:{{name}}</h2>
<h2>学校地址:{{address}}</h2>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
const vm = new Vue({
el: '#root',
data: {
name: '成都大学',
address: '成都'
}
})
</script>
</body>
1.7 事件处理
基本使用
<body>
<!--
事件的基本使用:
1.使用v-ont:xxx或@xxx绑定事件,其中xxx是事件名;
2.事件的回调需要配置在methods对象中,最终会在vm上;
3.methods中配置的函数,不要用箭头函数! 否则this就不是vm了;
4.methods中配置的函数,都是被Vue所管理的函数,this的指向是vm 或 组件实例对象;
5.@click="demo" 和 @click="demo($event)" 效果一致,但后者可以传参;
-->
<!-- 准备好一个容器 -->
<div id="root">
<h2>hello , {{name}} </h2>
<!-- <button v-on:click="showInfo">点我提示</button> -->
<button @click="showInfo1">点我提示1(不传参)</button>
<button @click="showInfo2($event,66)">点我提示2(传参)</button>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
const vm = new Vue({
el: '#root',
data: {
name: 'feng'
},
methods: {
showInfo1(event){
// console.log(event.target.innerText)
// console.log(this) //此处的this是vm
},
showInfo2(event,number){
console.log(event.target.innerText,number)
}
}
})
</script>
</body>
事件修饰符
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="../js/vue.js"></script>
<style>
*{
margin-top: 20px;
}
.demo1{
height: 50px;
background-color: skyblue;
}
.box1{
padding: 5px;
background-color: skyblue;
}
.box2{
padding: 5px;
background-color: orange;
}
</style>
</head>
<body>
<!--
Vue中的事件修饰符:
1.prevent: 阻止默认事件(常用);
2.stop: 阻止事件冒泡(常用);
3.once: 事件只触发一次(常用);
4.capture: 使用事件的捕获模式;
5.self: 只有event.target是当前操作的元素时才触发事件;
6.passive: 事件的默认行为立即执行,无需等待事件回调执行完毕;
-->
<!-- 准备好一个容器 -->
<div id="root">
<!-- 阻止默认事件(常用) -->
<a href="https://www.cnblogs.com/fengpeng123" @click.prevent="showInfo">点我提示</a>
<!-- 阻止事件冒泡(常用) -->
<div class="demo1" @click="showInfo">
<button @click.stop="showInfo">点我提示</button>
<!-- 修饰符可以连续写 -->
<a href="https://www.cnblogs.com/fengpeng123" @click.prevent.stop="showInfo">点我提示</a>
</div>
<!-- 事件只触发一次(常用) -->
<button @click.once="showInfo">点我提示</button>
<!-- 使用事件的捕获模式 -->
<div class="box1" @click.capture="showMsg(1)">
div1
<div class="box2" @click="showMsg(2)">
div2
</div>
</div>
<!-- 只有event.target是当前操作的元素时才触发事件 -->
<div class="demo1" @click.self="showInfo">
<button @click="showInfo">点我提示</button>
</div>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
new Vue({
el: '#root',
data: {
name: 'feng'
},
methods: {
showInfo(e){
// e.preventDefault() 阻止a标签跳转的默认行为
alert('hello')
},
showMsg(msg){
console.log(msg)
}
}
})
</script>
</body>
</html>
键盘事件
<body>
<!--
1.vue中常用的按键别名:
回车=> enter
删除=> delete(捕获"删除”和退格”键)
退出=>esc
空格=>space
换行=>tab (特殊,必须配合keydown去使用)
上=> up
下=> down
左=> left
右=> right
2.Vue未提供别名的按键,可以使用按键原始的key值去绑定,但注意要转为kebab-case(短横线命名)
3.系统修饰键(用法特殊):ctrl、alt、 shift、meta
(1).配合keyup使用:按下修饰健的同时,再按下其他键,随后释放其他键,事件才被触发。
(2).配合keydown使用: 正常触发事件。
4.也可以使用keyCode去指定具体的按键(不推荐)
5.Vue.config.keyCodes.自定义键名 = 键码,可以去定制按键别名
-->
<!-- 准备好一个容器 -->
<div id="root">
<input type="text" placeholder="按下回车提示输入" @keyup.enter="showInfo">
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
// Vue.config.keyCodes.huiche = 13 //定义了一个别名按键
new Vue({
el: '#root',
data: {
name: 'feng'
},
methods: {
showInfo(e){
console.log(e.target.value)
}
}
})
</script>
</body>
1.8 计算属性
姓名案例
<body>
<!-- 准备好一个容器 -->
<div id="root">
姓:<input type="text" v-model="firstName"> <br><br>
名:<input type="text" v-model="lastName"> <br><br>
全名: <span>{{fullName()}}</span>
<button @click="fullName">点我</button>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
new Vue({
el: '#root',
data: {
firstName: '张',
lastName: '三'
},
methods: {
fullName(){
return this.firstName + '-' + this.lastName
}
}
})
</script>
</body>
运行结果
基本使用
<body>
<!--
计算属性:
1.定义:要用的属性不存在,要通过已有属性计算得来。
2.原理:底层借助了0bjcet.defineproperty方法提供的getter和setter。
3.get函数什么时候执行?
(1).初次读取时会执行一次。
(2).当依赖的数据发生改变时会被再次调用。
4.优势:与methods实现相比,内部有缓存机制(复用),效率更高,调试方便。
5.备注:
1.计算属性最终会出现在vm上,直接读取使用即可。
2.如果计算属性要被修改,那必须写set函数去响应修改,且set中要引起计算时依赖的数据发生改变。
-->
<!-- 准备好一个容器 -->
<div id="root">
姓:<input type="text" v-model="firstName"> <br><br>
名:<input type="text" v-model="lastName"> <br><br>
全名: <span>{{fullName()}}</span>
<button @click="fullName">点我</button>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
const vm = new Vue({
el: '#root',
data: {
firstName: '张',
lastName: '三'
},
computed: {
fullName: {
//get有什么作用?当有人读取fullName时,get就会被调用,且返回值就作为fullName的值
//get什么时候调用?1、初次读取fullName时。 2、所依赖的数据发生变化时。
get(){
// console.log(this) //此处的this是vm
return this.firstName + '-' + this.lastName
},
//set什么时候调用? 当fullName被修改时。
set(value){
console.log('set',value)
const arr = value.split('-')
this.firstName = arr[0]
this.lastName = arr[1]
}
}
}
})
</script>
</body>
计算属性简写
<body>
<!-- 准备好一个容器 -->
<div id="root">
姓:<input type="text" v-model="firstName"> <br><br>
名:<input type="text" v-model="lastName"> <br><br>
全名: <span>{{fullName()}}</span>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
const vm = new Vue({
el: '#root',
data: {
firstName: '张',
lastName: '三'
},
computed: {
//完整写法
/* fullName: {
get(){
return this.firstName + '-' + this.lastName
},
set(value){
console.log('set',value)
const arr = value.split('-')
this.firstName = arr[0]
this.lastName = arr[1]
}
} */
/* 只有get时可以这样简写,类似于function形式,等同于get写法 */
fullName(){
return this.firstName + '-' + this.lastName
}
}
})
</script>
</body>
1.9 监视属性
天气案例
<body>
<!-- 准备好一个容器 -->
<div id="root">
<h2>今天天气很{{info}}</h2>
<!-- 绑定事件的时候: @xxx="yyy" yyy可以写一些简单的语句 -->
<!-- <button @click="this.isHot = !this.isHot">切换天气</button> -->
<button @click="changeWeather">切换天气</button>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
new Vue({
el: '#root',
data: {
isHot: true
},
computed: {
info(){
return this.isHot ? '炎热' : '凉爽'
}
},
methods: {
changeWeather(){
this.isHot = !this.isHot
}
},
})
</script>
</body>
运行结果
监视属性
<body>
<!--
监视属性watch:
1.当被监视的属性变化时,回调函数自动调用,进行相关操作
2.监视的属性必须存在,才能进行监视!!
3.监视的两种写法:
(1).new Vue时传入watch配置
(2).通过vm.$watch监视
-->
<!-- 准备好一个容器 -->
<div id="root">
<h2>今天天气很{{info}}</h2>
<button @click="changeWeather">切换天气</button>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
const vm = new Vue({
el: '#root',
data: {
isHot: true
},
computed: {
info(){
return this.isHot ? '炎热' : '凉爽'
}
},
methods: {
changeWeather(){
this.isHot = !this.isHot
}
},
/* watch: {
isHot: {
immediate: true, //初始化时让handler调用一下
//handler什么时候调用? 当isHot发生改变时。
handler(newValue,oldValue){
console.log('isHot被修改了',newValue,oldValue)
}
}
} */
})
vm.$watch('isHot',{
immediate: true, //初始化时让handler调用一下
//handler什么时候调用? 当isHot发生改变时。
handler(newValue,oldValue){
console.log('isHot被修改了',newValue,oldValue)
}
})
</script>
</body>
运行结果
深度监视
<body>
<!--
深度监视:
(1).vue中的watch默认不监测对象内部值的改变(一层)。
(2).配置deep:true可以监测对象内部值改变(多层)。
备注:
(1).Vue自身可以监测对象内部值的改变,但Vue提供的watch默认不可以!
(2).使用watch时根据数据的具体结构,决定是否采用深度监视。
-->
<!-- 准备好一个容器 -->
<div id="root">
<h2>今天天气很{{info}}</h2>
<button @click="changeWeather">切换天气</button>
<hr>
<h3>a的值是:{{numbers.a}}</h3>
<button @click="numbers.a++">点我让a+1</button>
<h3>b的值是:{{numbers.b}}</h3>
<button @click="numbers.b++">点我让b+1</button>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
const vm = new Vue({
el: '#root',
data: {
isHot: true,
numbers: {
a: 1,
b: 1
}
},
computed: {
info(){
return this.isHot ? '炎热' : '凉爽'
}
},
methods: {
changeWeather(){
this.isHot = !this.isHot
}
},
watch: {
isHot: {
// immediate: true, //初始化时让handler调用一下
//handler什么时候调用? 当isHot发生改变时。
handler(newValue,oldValue){
console.log('isHot被修改了',newValue,oldValue)
}
},
//监视多级结构中某个属性的变化
/* 'numbers.a': {
handler(){
console.log('a被改变了')
}
} */
//监视多级结构中所有属性的变化
numbers: {
deep: true,
handler(){
console.log('numbers改变了')
}
}
}
})
</script>
</body>
运行测试
简写
<body>
<!-- 准备好一个容器 -->
<div id="root">
<h2>今天天气很{{info}}</h2>
<button @click="changeWeather">切换天气</button>
<hr>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
const vm = new Vue({
el: '#root',
data: {
isHot: true,
},
computed: {
info(){
return this.isHot ? '炎热' : '凉爽'
}
},
methods: {
changeWeather(){
this.isHot = !this.isHot
}
},
watch: {
//正常写法
/* isHot: {
// immediate: true, //初始化时让handler调用一下
// deep: true, //深度监视
handler(newValue,oldValue){
console.log('isHot被修改了',newValue,oldValue)
}
}, */
//简写
/* isHot(newValue,oldValue){
console.log('isHot被修改了',newValue,oldValue)
} */
}
})
//正常写法
/* vm.$watch('isHot',{
immediate: true, //初始化时让handler调用一下
deep: true, //深度监视
handler(newValue,oldValue){
console.log('isHot被修改了',newValue,oldValue)
}
}) */
//简写
vm.$watch('isHot',function(newValue,oldValue){
console.log('isHot被修改了',newValue,oldValue)
})
</script>
</body>
watch,computed对比
<body>
<!--
computed和watch之间的区别:
1.computed能完成的功能,watch都可以完成。
2.watch能完成的功能,computed不一定能完成,例如: watch可以进行异步操作。
两个重要的小原则:
1.所被Vue管理的函数,最好写成普通函数,这样this的指向才是vm 或 组件实例对象。
2.所有不被Vue所管理的函数(定时器的回调函数、ajax的回调函数等、Promise的回调函数),最好写成箭头函数,
这样this的指向才是 vm 或 组件实例对象。
-->
<!-- 准备好一个容器 -->
<div id="root">
姓:<input type="text" v-model="firstName"> <br><br>
名:<input type="text" v-model="lastName"> <br><br>
全名: <span>{{fullName}}</span>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
const vm = new Vue({
el: '#root',
data: {
firstName: '张',
lastName: '三',
fullName: '张-三'
},
watch: {
firstName(val){
setTimeout(() => {
this.fullName = val + '-' + this.lastName
}, 1000);
},
lastName(val){
this.fullName = this.firstName + '-' + val
}
}
})
</script>
</body>
1.10 样式绑定
绑定class样式
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="../js/vue.js"></script>
<style>
.basic{
width: 400px;
height: 100px;
border: 1px solid black;
}
.happy{
width: 400px;
height: 100px;
border: 1px solid red;
}
.sad{
width: 400px;
height: 100px;
border: 1px solid grey;
}
.normal{
width: 400px;
height: 100px;
border: 1px solid blue;
}
.feng1{
width: 400px;
height: 100px;
border: 1px solid rebeccapurple;
}
.feng2{
width: 400px;
height: 100px;
border: 1px solid beige;
}
.feng3{
width: 400px;
height: 100px;
border: 1px solid olive;
}
</style>
</head>
<body>
<!-- 准备好一个容器 -->
<div id="root">
<!-- 绑定class样式 --字符串写法,适用于:样式的类名不确定,需要动态指定 -->
<div class="basic" :class="mood" @click="changeMode">{{name}}</div><br><br>
<!-- 绑定class样式 --数组写法,适用于:要绑定的样式个数不确定,名字也不确定 -->
<div class="basic" :class="classArr">{{name}}</div>
<!-- 绑定class样式 --对象写法,适用于:要绑定的样式个数确定,名字也确定,但是动态决定用不用-->
<div class="basic" :class="classObj">{{name}}</div>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
new Vue({
el: '#root',
data: {
name: 'feng',
mood: 'normal',
classArr: ['feng1','feng2','feng3'],
classObj: {
feng1: false,
feng2: false,
}
},
methods: {
changeMood(){
const arr = ['happy','sad','normal']
//取0,1,2随机数
this.mood = arr[Math.floor(Math.random()*3)]
}
},
})
</script>
</body>
绑定style样式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="../js/vue.js"></script>
<style>
.basic{
width: 400px;
height: 100px;
border: 1px solid black;
}
.happy{
width: 400px;
height: 100px;
border: 1px solid red;
}
.sad{
width: 400px;
height: 100px;
border: 1px solid grey;
}
.normal{
width: 400px;
height: 100px;
border: 1px solid blue;
}
.feng1{
width: 400px;
height: 100px;
border: 1px solid rebeccapurple;
}
.feng2{
width: 400px;
height: 100px;
border: 1px solid beige;
}
.feng3{
width: 400px;
height: 100px;
border: 1px solid olive;
}
</style>
</head>
<body>
<!--
绑定样式:
1.class样式:
写法:class="xxx"xXx可以是字符串、对象、数组。
字符串写法适用于:类名不确定,要动态获取。
对象写法适用于:要绑定多个样式,个数不确定,名字也不确定。
数组写法适用于:要绑定多个样式,个数确定,名字也确定,但不确定用不用。
2. style样式
:style="{fontsize: xxx}"其中xxx是动态值。
:style="[a,b]"其中a、b是样式对象(不能随便写,必须是存在的)。
-->
<!-- 准备好一个容器 -->
<div id="root">
<!-- 绑定class样式 --字符串写法,适用于:样式的类名不确定,需要动态指定 -->
<div class="basic" :class="mood" @click="changeMode">{{name}}</div><br><br>
<!-- 绑定class样式 --数组写法,适用于:要绑定的样式个数不确定,名字也不确定 -->
<div class="basic" :class="classArr">{{name}}</div><br><br>
<!-- 绑定class样式 --对象写法,适用于:要绑定的样式个数确定,名字也确定,但是动态决定用不用-->
<div class="basic" :class="classObj">{{name}}</div><br><br>
<!-- 绑定style样式--对象写法-->
<div class="basic" :style="styleObj">{{name}}</div><br><br>
<!-- 绑定style样式--数组写法-->
<div class="basic" :style="[styleObj,styleObj2]">{{name}}</div><br><br>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
new Vue({
el: '#root',
data: {
name: 'feng',
mood: 'normal',
classArr: ['feng1','feng2','feng3'],
classObj: {
feng1: false,
feng2: false,
},
styleObj: {
fontSize: '40px', //css中的font-size写成驼峰写法
color: 'red',
},
styleObj2: {
backgroundColor: 'orange'
}
},
methods: {
changeMood(){
const arr = ['happy','sad','normal']
this.mood = arr[Math.floor(Math.random()*3)]
}
},
})
</script>
</body>
</html>
1.11 条件渲染
<body>
<!--
条件渲染:
1.v-if
写法:
(1).v-if="表达式"
(2).v-else-if="表达式"(3).v-else="表达式"适用于:切换频率较低的场景。
特点:不展示的DOM元素直接被移除。
注意:v-if可以和:v-else-if、v-else一起使用,但要求结构不能被"打断”。
2.v-show
写法:v-show="表达式"
适用于:切换频率较高的场景。
特点:不展示的DOM元素未被移除,仅仅是使用样式隐藏掉
3.备注:
使用v-if的时,元素可能无法获取到,而使用v-show一定可以获取到。
-->
<!-- 准备好一个容器 -->
<div id="root">
<h2>当前的n值是{{n}}</h2>
<button @click="n++">点我n+1</button>
<!-- 使用v-show做条件渲染 -->
<!-- <h2 v-show="false">欢迎你~ {{name}}</h2> -->
<!-- <h2 v-show="1 === 1">欢迎你~ {{name}}</h2> -->
<!-- 使用v-if做条件渲染 -->
<!-- <h2 v-if="false">欢迎你~ {{name}}</h2> -->
<!-- <h2 v-if="1 === 1">欢迎你~ {{name}}</h2> -->
<!-- v-else和v-else-if -->
<!-- <div v-if="n === 1">Angular</div>
<div v-else-if="n === 2">React</div>
<div v-else-if="n === 3">Vue</div>
<div v-else>haha</div> -->
<!-- v-if与template的配合使用,template只能和v-if配合使用,不能和v-show配置使用 -->
<!-- template不会破坏页面结构(template在页面中不会有元素存在) -->
<template v-if="n === 1">
<h2>你好</h2>
<h2>feng</h2>
<h2>成都</h2>
</template>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
new Vue({
el: '#root',
data: {
name: 'feng',
n: 0
}
})
</script>
</body>
运行结果
1.12 列表
列表渲染
<body>
<!--
v-for指令:
1.用于展示列表数据
2.语法: v-for="(item,index) in xxx" :key="yyy"
3.可遍历: 数组、对象、字符串(用的很少)、指定次数(用的很少)
-->
<!-- 准备好一个容器 -->
<div id="root">
<!-- 遍历数组 -->
<h2>人员列表</h2>
<ul>
<li v-for="(p,index) in persons" :key="index">
{{p.name}}-{{p.age}}
</li>
</ul>
<!-- 遍历对象 -->
<h2>汽车信息</h2>
<ul>
<li v-for="(value,k) of car" :key="k">
{{k}}-{{value}}
</li>
</ul>
<!-- 遍历字符串 -->
<h2>测试遍历字符串</h2>
<ul>
<li v-for="(char,index) of str" :key="index">
{{char}}-{{index}}
</li>
</ul>
<!-- 遍历指定次数 -->
<h2>测试遍历指定次数</h2>
<ul>
<li v-for="(number,index) of 5" :key="index">
{{index}}-{{number}}
</li>
</ul>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
new Vue({
el: '#root',
data: {
persons: [
{id: '001',name: '张三',age: 18},
{id: '002',name: '李四',age: 19},
{id: '003',name: '王五',age: 20}
],
car: {
name: '汽车',
price: '20万',
color: '黑色'
},
str: 'hello'
}
})
</script>
</body>
key作用原理
<body>
<!--
面试题:react、vue中的key有什么作用?(key的内部原理)
1.虚拟DOM中key的作用:
key是虚拟DOM对象的标识,当状态中的数据发生变化时,Vue会根据【新数据】生成【新的虚拟DOM】,
随后Vue进行【新虚拟DOM】与【旧虚拟DOM】的差异比较,
比较规则如下:
2.对比规则:
(1).旧虚拟DOM中找到了与新虚拟DOM相同的key:
1.若虚拟DOM中内容没变,直接使用之前的真实DOM !
2.若虚拟DOM中内容变了,则生成新的真实DOM,随后替换掉页面中之前的真实DOM。
(2).旧虚拟DOM中未找到与新虚拟DOM相同的key
创建新的真实DOM,随后渲染到到页面。
3.用index作为key可能会引发的问题:
1.若对数据进行:逆序添加、逆序删除等破坏顺序操作:
会产生没有必要的真实DOM更新 ==> 界面效果没问题,但效率低。
2.如果结构中还包含输入类的DOM:
会产生错误DOM更新==>界面有问题。
4.开发中如何选择key? :
1.最好使用每条数据的唯一标识作为key,比如id、手机号、身份证号、学号等唯一值。
2.如果不存在对数据的逆序添加、逆序删除等破坏顺序操作,仅用于渲染列表用于展示,
使用index作为key是没有问题的。
-->
<!-- 准备好一个容器 -->
<div id="root">
<!-- 遍历数组 -->
<h2>人员列表(遍历数组)</h2>
<button @click.once="add">添加一个老刘</button>
<ul>
<li v-for="(p,index) in persons" :key="index">
{{p.name}}-{{p.age}}
<input type="text">
</li>
</ul>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
new Vue({
el: '#root',
data: {
persons: [
{id: '001',name: '张三',age: 18},
{id: '002',name: '李四',age: 19},
{id: '003',name: '王五',age: 20}
],
},
methods: {
add(){
const p = {id: '004',name: '老刘',age: 40}
this.persons.unshift(p)
}
},
})
</script>
</body>
运行结果
列表过滤
<body>
<!-- 准备好一个容器 -->
<div id="root">
<!-- 遍历数组 -->
<h2>人员列表</h2>
<input type="text" placeholder="请输入名字" v-model="keyWord">
<ul>
<li v-for="(p,index) in filPersons" :key="index">
{{p.name}}-{{p.age}}-{{p.sex}}
</li>
</ul>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
//用watch实现
/* new Vue({
el: '#root',
data: {
keyWrod: '',
persons: [
{id: '001',name: '马冬梅',age: 19,sex: '女'},
{id: '002',name: '周冬雨',age: 20,sex: '女'},
{id: '003',name: '周杰伦',age: 21,sex: '男'},
{id: '004',name: '温兆伦',age: 22,sex: '男'}
],
filPersons: []
},
watch: {
keyWrod: {
immediate: true,
handler(val){
this.filPersons = this.persons.filter((p) => {
return p.name.indexOf(val) !== -1
})
}
}
}
}) */
//使用computed实现
new Vue({
el: '#root',
data: {
keyWord: '',
persons: [
{id: '001',name: '马冬梅',age: 19,sex: '女'},
{id: '002',name: '周冬雨',age: 20,sex: '女'},
{id: '003',name: '周杰伦',age: 21,sex: '男'},
{id: '004',name: '温兆伦',age: 22,sex: '男'}
],
},
computed: {
filPersons() {
return this.persons.filter((p) => {
return p.name.indexOf(this.keyWord) !== -1
})
}
}
})
</script>
</body>
运行结果
列表排序
<body>
<!-- 准备好一个容器 -->
<div id="root">
<!-- 遍历数组 -->
<h2>人员列表</h2>
<input type="text" placeholder="请输入名字" v-model="keyWord">
<button @click=" sortType = 2 ">年龄升序</button>
<button @click=" sortType = 1 ">年龄降序</button>
<button @click=" sortType = 0 ">原顺序</button>
<ul>
<li v-for="(p,index) in filPersons" :key="index">
{{p.name}}-{{p.age}}-{{p.sex}}
</li>
</ul>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
//使用computed实现
new Vue({
el: '#root',
data: {
keyWord: '',
sortType: 0, //0 原顺序 1 降序 2 升序
persons: [
{id: '001',name: '马冬梅',age: 30,sex: '女'},
{id: '002',name: '周冬雨',age: 31,sex: '女'},
{id: '003',name: '周杰伦',age: 18,sex: '男'},
{id: '004',name: '温兆伦',age: 19,sex: '男'}
],
},
computed: {
filPersons() {
const arr = this.persons.filter((p) => {
return p.name.indexOf(this.keyWord) !== -1
})
//判断一下是否需要排序
if(this.sortType){
arr.sort((p1,p2) => {
return this.sortType === 1 ? p2.age - p1.age : p1.age - p2.age
})
}
return arr
}
}
})
</script>
</body>
运行结果
vue检测数据原理
<body>
<script type="text/javascript">
let data = {
name: '成都大学',
address: '成都'
}
//创建一个监视的实例对象,用于监视data中属性的变化
const obs = new Observer(data)
console.log(obs)
//准备一个vm实例对象
let vm = {}
vm._data = data = obs
function Observer(obj){
//汇总对象中所有的属性形成一个数组
const keys = Object.keys(obj)
//遍历
keys.forEach((k) => {
Object.defineProperty(this,k,{
get(){
return obj[k]
},
set(val){
console.log(`${k}被改了,我要去解析模板,生成虚拟的DOM....我要开始忙了`)
obj[k] = val
}
})
})
}
</script>
</body>
总的来说,就是通过对象的getter,setter进行监视。
Vue.set()使用
<body>
<!-- 准备好一个容器 -->
<div id="root">
<h1>学校信息</h1>
<h2>学校名称: {{name}}</h2>
<h2>学校地址: {{address}}</h2>
<h2>校长是: {{leader}}</h2>
<hr/>
<h1>学生信息</h1>
<button @click="addSex">添加一个性别属性,默认值是男</button>
<h2>学生姓名:{{student.name}}</h2>
<h2 v-if="student.sex">学生性别:{{student.sex}}</h2>
<h2>学生年龄:真实{{student.age.rAge}}, 对外{{student.age.sAge}}</h2>
<h2>朋友们</h2>
<ul>
<li v-for="(f,index) in student.friends" :key="index">
{{f.name}}-{{f.age}}
</li>
</ul>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
const vm = new Vue({
el: '#root',
data: {
name: '成都大学',
address: '成都',
student: {
name: 'tom',
age: {
rAge: 40,
sAge: 29,
},
friends:[
{name:'jerry',age:35},
{name:'tony',age:36}
]
}
},
methods: {
addSex(){
// Vue.set(this.student,'sex','男')
this.$set(this.student,'sex','男')
}
},
})
</script>
</body>
运行结果
注意点:Vue.set第一个属性不能是vm,不能是data中的直接属性,只能是data里面的一个对象中的属性
总结Vue监视数据
<body>
<!--
vue监视数据的原理:
1. vue会监视data中所有层次的数据。
2.如何监测对象中的数据?
通过setter实现监视,且要在new Vue时就传入要监测的数据。
(1).对象中后追加的属性,Vue默认不做响应式处理
(2).如需给后添加的属性做响应式,请使用如下API:
Vue.set(target. propertyName/index, value)或
vm.$set(target,propertyName/index,value)
3.如何监测数组中的数据?
通过包裹数组更新元素的方法实现,本质就是做了两件事:
(1).调用原生对应的方法对数组进行更新。
(2).重新解析模板,进而更新页面。
4.在Vue修改数组中的某个元素一定要用如下方法:
1.使用这些API:push()、pop()、shift()、unshift()、splice()、sort()、reverse()
2.Vue.set() 或 vm.$set()
特别注意:Vue.set()和 vm.$set()不能给vm或 vm的根数据对象 添加属性!!!
-->
<!-- 准备好一个容器 -->
<div id="root">
<h1>学生信息</h1>
<button @click="student.age++">年龄+1岁</button>
<button @click="addSex">添加一个性别属性,默认值:男</button>
<button @click="addFriend">在列表首位添加一个朋友</button>
<button @click="updateFirstFriendName">修改第一个朋友的名字为:张三</button>
<button @click="addHobby">添加一个爱好</button>
<button @click="updateHobby">修改一个爱好为:开车</button>
<button @click="removeSmoke">过滤掉爱好中的游戏</button>
<h2>学生姓名:{{student.name}}</h2>
<h2>学生年龄:{{student.age}}</h2>
<h2 v-if="student.sex">学生性别:{{student.sex}}</h2>
<h2>爱好: </h2>
<ul>
<li v-for="(h,index) in student.hobby" :key="index">
{{h}}
</li>
</ul>
<h2>朋友们</h2>
<ul>
<li v-for="(f,index) in student.friends" :key="index">
{{f.name}}-{{f.age}}
</li>
</ul>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
const vm = new Vue({
el: '#root',
data: {
student: {
name: 'tom',
age: 18,
hobby: ['游戏','音乐','电影'],
friends:[
{name:'jerry',age:35},
{name:'tony',age:36}
]
}
},
methods: {
addSex(){
Vue.set(this.student,'sex','男')
},
addFriend(){
this.student.friends.unshift({name:'jack',age:70})
},
updateFirstFriendName(){
this.student.friends[0].name='张三'
},
addHobby(){
this.student.hobby.push('直播')
},
updateHobby(){
// this.student.hobby.splice(0,1,'开车') //从数组的第0个开始,删除1个,再插入1个开车
Vue.set(this.student.hobby,0,'开车')
},
removeSmoke(){
this.student.hobby = this.student.hobby.filter((h) => {
return h !== '游戏'
})
}
},
})
</script>
</body>
1.13 收集表单数据
<body>
<!--
收集表单数据:
若:<input type="text"/>,则v-model收集的是value值,用户输入的就是value值。
若:<input type="radio"/>,则v-model收集的是value值,且要给标签配置value值。
若: <input type="checkbox" />
1.没有配置input的value属性,那么收集的就是checked(勾选or未勾选,是布尔值)
2.配置input的value属性:
(1)v-model的初始值是非数组,那么收集的就是checked(勾选or未勾选,是布尔值)
(2)v-model的初始值是数组,那么收集的的就是value组成的数组
备注:v-model的三个修饰符:
lazy: 失去焦点再收集数据
number: 输入字符串转为有效的数字
trim: 输入首尾空格过滤
-->
<!-- 准备好一个容器 -->
<div id="root">
<!-- prevent: 阻止默认行为 -->
<form @submit.prevent="demo">
<!-- v-model.trim 去掉前后空格 -->
账号:<input type="text" v-model.trim="userInfo.account"><br>
密码:<input type="password" v-model="userInfo.password"><br>
<!-- type="number" 控制输入的是数字, v-model.number 将输入的数字字符转成数字-->
年龄:<input type="number" v-model.number="userInfo.age"><br>
性别:
男 <input type="radio" name="sex" v-model="userInfo.sex" value="male">
女 <input type="radio" name="sex" v-model="userInfo.sex" value="female"><br>
爱好:
学习<input type="checkbox" v-model="userInfo.hobby" value="study">
打游戏<input type="checkbox"v-model="userInfo.hobby" value="game">
吃饭<input type="checkbox"v-model="userInfo.hobby" value="eat"><br>
所属校区
<select v-model="userInfo.city">
<option value="">请选择校区</option>
<option value="beijing">北京</option>
<option value="shanghai">上海</option>
<option value="shenzhen">深圳</option>
<option value="wuhai">武汉</option>
</select><br>
其他信息
<!-- v-model.lazy 当输入框失去焦点之后,才会获取输入框中的数据 -->
<textarea v-model.lazy="userInfo.other"></textarea><br>
<input type="checkbox" v-model="userInfo.agree"> 阅读并接受<a href="http://www.baidu.com">《用户协议》</a><br>
<button>提交</button>
</form>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
new Vue({
el: '#root',
data: {
userInfo: {
account: '',
password: '',
sex: 'female',
hobby: [],
city: 'beijing',
other: '',
agree: '',
age: 15,
}
},
methods: {
demo(){
console.log(JSON.stringify(this.userInfo))
}
},
})
</script>
</body>
运行结果
1.14 过滤器
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript" src="../js/dayjs.min.js"></script>
</head>
<body>
<!--
过滤器:
定义:对要显示的数据进行特定格式化后再显示(适用于一些简单逻辑的处理)。
语法:
1.注册过滤器:Vue.filter(name,callback)或new Vue{filters:{}}
2.使用过滤器:{{ xxx│过滤器名}} 或 v-bind:属性 = "xxx │ 过滤器名"
备注:
1.过滤器也可以接收额外参数、多个过滤器也可以串联
2.并没有改变原本的数据,是产生新的对应的数据。
-->
<!-- 准备好一个容器 -->
<div id="root">
<h2>显示格式化后的时间</h2>
<!-- 计算属性实现 -->
<h3>现在是:{{fmtTime}}</h3>
<!-- methods实现 -->
<h3>现在是:{{getFmtTime()}}</h3>
<!-- 过滤器实现 -->
<h3>现在是:{{time | timeFormater}}</h3>
<!-- 过滤器实现(传参) -->
<h3>现在是:{{time | timeFormater('YYYY_MM_DD') | mySlice }}</h3>
<h3 :x="msg">hello</h3>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
//全局过滤器
Vue.filter('mySlice',function(value){
return value.slice(0,4)
})
new Vue({
el: '#root',
data: {
time: 1691505105731, //时间戳
msg: 'hello,world'
},
computed: {
fmtTime(){
return dayjs(this.time).format('YYYY-MM-DD HH:mm:ss')
}
},
methods: {
getFmtTime(){
return dayjs(this.time).format('YYYY-MM-DD HH:mm:ss')
}
},
//局部过滤器
filters: {
timeFormater(value,str='YYYY-MM-DD HH:mm:ss'){ //str为第二个参数,如果传了值就使用传值,如果没有传值,就使用这里的默认值
return dayjs(value).format(str)
},
/* mySlice(value){
return value.slice(0,4)
} */
}
})
</script>
</body>
运行结果
1.15 内置指令
v-text
<body>
<!--
我们学过的指令:
v-bind:单向绑定解析表达式,可简写为:xxx
v-model :双向数据绑定
v-for :遍历数组/对象/字符串
v-on:绑定事件监听,可简写为@
v-if:条件渲染(动态控制节点是否存在)
v-else:条件渲染(动态控制节点是否存在)
v-show:条件渲染(动态控制节点是否展示)
v-text指令:
1.作用:向其所在的节点中渲染文本内容。
2.与插值语法的区别:v-text会替换掉节点中的内容,{{xx}}则不会。
-->
<!-- 准备好一个容器 -->
<div id="root">
<div>{{name}}</div>
<div v-text="name"></div>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
new Vue({
el: '#root',
data: {
name: 'feng'
}
})
</script>
</body>
运行结果
v-html
cookie
<body>
<!--
v-html指令:
1.作用: 向指定节点中渲染包含html结构的内容。
2.与插值语法的区别:
(1).v-html会替换掉节点中所有的内容,{{xx}}则不会。
(2).v-htm1可以识别html结构。
3.严重注意: v-html有安全性问题!!!!
(1).在网站上动态渲染任意HTML是非常危险的,容易导致XSS攻击。
(2).一定要在可信的内容上使用v-html,永不要用在用户提交的内容上!
-->
<!-- 准备好一个容器 -->
<div id="root">
<div>你好,{{name}}</div>
<div v-html="str"></div>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
new Vue({
el: '#root',
data: {
name: 'feng',
str: '<h3>你好啊!!</h3>'
}
})
</script>
</body>
v-cloak
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
[v-cloak]{
<!-- 设置初始样式为隐藏 -->
display: none;
}
</style>
</head>
<body>
<!--
v-cloak指令(没有值):
1.本质是一个特殊属性,Vue实例创建完毕并接管容器后,会删掉v-cloak属性。
2.使用css配合v-cloak可以解次网速慢时页面展示出{{xxx}}的问题。
-->
<!-- 准备好一个容器 -->
<div id="root">
<h2 v-cloak>{{name}}</h2>
</div>
<!-- 这个地方需要特殊处理,相当于外部引入Vue -->
<script type="text/javascript" src="http://localhost:8080/resource/5s/vue.js"></script>
</body>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
new Vue({
el: '#root',
data: {
name: 'feng',
}
})
</script>
</html>
v-once
<body>
<!--
v-once指令:
1.v-once所在节点在初次动态渲染后,就视为静态内容了。
2.以后数据的改变不会引起v-once所在结构的更新,可以用于优化性能。
-->
<!-- 准备好一个容器 -->
<div id="root">
<h2 v-once>初始化的n值是:{{n}}</h2>
<h2>当前的n值是:{{n}}</h2>
<button @click="n++">点我n+1</button>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
new Vue({
el: '#root',
data: {
n: 1
}
})
</script>
</body>
运行结果
v-pre
<body>
<!--
v-pre指令:
1.跳过其所在节点的编译过程。
2.可利用它跳过: 没有使用指令语法、没有使用插值语法的节点,会加快编译。
-->
<!-- 准备好一个容器 -->
<div id="root">
<h2 v-pre>vue很复杂</h2>
<h2>当前的n值是:{{n}}</h2>
<button @click="n++">点我n+1</button>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
new Vue({
el: '#root',
data: {
n: 1
}
})
</script>
</body>
运行结果
1.16 自定义指令
函数式
<body>
<!--
需求1:定义一个v-big指令,和v-text功能类似,但会把绑定的数值放大10倍。
需求2:定义一个v-fbind指令,和v-bind功能类似,但可以让其所绑定的input元素默认获取焦点。
-->
<!-- 准备好一个容器 -->
<div id="root">
<h2>当前的n值是: <span v-text="n"></span> </h2>
<h2>放大10倍后的n值是:<span v-big="n"></span></h2>
<button @click="n++">点我n+1</button>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
new Vue({
el: '#root',
data: {
name: 'feng',
n: 1
},
directives: {
//big函数何时会被调用?
//1.指令与元素成功绑定时(一上来)。2.指令所在的模板被重新解析时(例如n对应模板中的name发生了改变,big函数也会被调用)。
big(element,binding){//element: <span></span>
element.innerText = binding.value * 10
}
}
})
</script>
</body>
运行结果
对象式
<body>
<!--
需求1:定义一个v-big指令,和v-text功能类似,但会把绑定的数值放大10倍。
需求2:定义一个v-fbind指令,和v-bind功能类似,但可以让其所绑定的input元素默认获取焦点。
-->
<!-- 准备好一个容器 -->
<div id="root">
<h2>当前的n值是: <span v-text="n"></span> </h2>
<h2>放大10倍后的n值是:<span v-big="n"></span></h2>
<button @click="n++">点我n+1</button>
<hr/>
<input type="text" v-fbind:value="n" >
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
new Vue({
el: '#root',
data: {
name: 'feng',
n: 1
},
directives: {
//big函数何时会被调用?
//1.指令与元素成功绑定时(一上来)。2.指令所在的模板被重新解析时(例如n对应模板中的name发生了改变,big函数也会被调用)。
big(element,binding){
element.innerText = binding.value * 10
},
fbind: {
//指令与元素成功绑定时(一上来)
bind(element,binding){
element.value = binding.value
},
//指令所在元素被插入页面时
inserted(element,binding){
element.focus()
},
//指令所在的模板被重新解析时
update(element,binding){
element.value = binding.value
}
}
}
})
</script>
</body>
运行结果
总结
<body>
<!--
需求1:定义一个v-big指令,和v-text功能类似,但会把绑定的数值放大10倍。
需求2:定义一个v-fbind指令,和v-bind功能类似,但可以让其所绑定的input元素默认获取焦点。
自定义指令总结:
一、定义语法:
(1).局部指令:
new Vue({
new Vue({
directives:{指令名:配置对象}或directives{指令名,回调函数}
})
})
(2).全局指令:
Vue.directive(指令名,配置对象)或 Vue.directive(指令名,回调函数)
二、配置对象中常用的3个回调;
(1).bind:指令与元素成功绑定时调用。
(2).inserted:指令所在元素被插入页面时调用。(3).update:指令所在模板结构被重新解析时调用。
三、备注:
1.指令定义时不加v-,但使用时要加v-;
2.指令名如果是多个单词,要使用kebab-case命名方式,不要用camelCase命名。
-->
<!-- 准备好一个容器 -->
<div id="root">
<h2>当前的n值是: <span v-text="n"></span> </h2>
<h2>放大10倍后的n值是:<span v-big="n"></span></h2>
<button @click="n++">点我n+1</button>
<hr/>
<input type="text" v-fbind:value="n" >
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
//定义全局指令
Vue.directive('fbind',{
//指令与元素成功绑定时(一上来)
bind(element,binding){
element.value = binding.value
},
//指令所在元素被插入页面时
inserted(element,binding){
element.focus()
},
//指令所在的模板被重新解析时
update(element,binding){
element.value = binding.value
}
})
//定义全局指令
Vue.directive('big',function(element,binding){
console.log('big',this) //注意此处的this是window
element.innerText = binding.value * 10
})
new Vue({
el: '#root',
data: {
name: 'feng',
n: 1
},
directives: {
//big函数何时会被调用?
//1.指令与元素成功绑定时(一上来)。2.指令所在的模板被重新解析时(例如n对应模板中的name发生了改变,big函数也会被调用)。
/* 'big-number'(element,binding){ //如果中间有 - 符号,需要属性名需要加上引号''
element.innerText = binding.value * 10
}, */
/* big(element,binding){
console.log('big',this) //注意此处的this是window
element.innerText = binding.value * 10
}, */
/* fbind: {
//指令与元素成功绑定时(一上来)
bind(element,binding){
element.value = binding.value
},
//指令所在元素被插入页面时
inserted(element,binding){
element.focus()
},
//指令所在的模板被重新解析时
update(element,binding){
element.value = binding.value
}
} */
}
})
</script>
</body>
1.17 生命周期
引出生命周期
<body>
<!--
生命周期:
1.又名:生命周期回调函数、生命周期函数、生命周期钩子。
2.是什么:Vue在关键时刻帮我们调用的一些特殊名称的函数。
3.生命周期函数的名字不可更改,但函数的具体内容是程序员根据需求编写的。
4.生命周期函数中的this指向是vm 或 组件实例对象。
-->
<!-- 准备好一个容器 -->
<div id="root">
<!-- :style="{opacity: opacity}" -->
<h2 :style="{opacity}">欢迎学习Vue</h2>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
const vm = new Vue({
el: '#root',
data: {
opacity: 1
},
methods: {
/* change(){
//vue管理的change没用箭头函数,定时器不归vue管理用箭头函数不影响,所有this还是vm
setInterval(() => {
this.opacity -= 0.01
if(this.opacity <= 0){
this.opacity = 1
}
}, 16)
} */
},
//Vue完成模板的解析并把初始的真实DOM元素放入页面后(挂载完毕)调用mounted
mounted() {
//this从箭头函数往外找,Vue在mounted中帮我们维护好了,this就是vm
setInterval(() => {
this.opacity -= 0.01
if(this.opacity <= 0){
this.opacity = 1
}
}, 16)
},
})
//开启定时器
//通过外部的定时器实现(不推荐)
/* setInterval(() => {
vm.opacity -= 0.01
if(vm.opacity <= 0){
vm.opacity = 1
}
}, 16); */
</script>
</body>
运行结果
分析生命周期
总结生命周期
<body>
<!--
常用的生命周期钩子:
1.mounted:发送ajax请求、启动定时器、绑定自定义事件、订阅消息等【初始化操作】。
2.beforeDestroy:清除定时器、解绑自定义事件、取消订阅消息等【收尾工作】。
关于销毁Vue实例
1.销毁后借助vue开发者工具看不到任何信息。
2.销毁后自定义事件会失效,但原生DOM事件依然有效。
3.一般不会在beforeDestroy操作数据,因为即便操作数据,也不会再触发更新流程了。
-->
<!-- 准备好一个容器 -->
<div id="root">
<h2 :style="{opacity}">欢迎学习Vue</h2>
<button @click="opacity = 1">透明度设置为1</button>
<button @click="stop">点我停止变换</button>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
const vm = new Vue({
el: '#root',
data: {
opacity: 1
},
methods: {
stop(){
this.$destroy()
}
},
//Vue完成模板的解析并把初始的真实DOM元素放入页面后(挂载完毕)调用mounted
mounted() {
//this从箭头函数往外找,Vue在mounted中帮我们维护好了,this就是vm
this.timer = setInterval(() => {
this.opacity -= 0.01
if(this.opacity <= 0){
this.opacity = 1
}
}, 16)
},
beforeDestroy() {
console.log('vm即将销毁')
//销毁定时器
clearInterval(this.timer)
},
})
</script>
</body>
2 组件化编程
2.1 组件的理解
2.2 非单文件组件
一个文件中包含有n个组件。
//组件可能被多次调用
//组件中为什么要把data写成函数式:每次调用都是返回一个新的对象,如果更改了x1中的a值,x2中的a值不会变化。反之data使用对象式写法,改变x1的a值,x2中的a值也会发生变化。
function data(){
return {
a: 1,
b: 2
}
}
const x1 = data()
const x2 = data()
<body>
<!--
Vue中使用组件的三大步骤:
一、定义组件(创建组件)
二、注册组件
三、使用组件(写组件标签)
一、如何定义一个组件?
使用vue.extend(options)创建,其中options和new Vue(options)时传入的那个options几乎一样,但区别如下:
1.el不要写,为什么? -----最终所有的组件都要经过一个vm的管理,由vm中的el决定服务哪个容器
2.data必须写成函数,为什么? ----避免组件被复用时,数据存在引用关系。
备注:使用template可以配置组件结构。
二、如何注册组件?
1.局部注册: 靠new Vue的时候传入components选项
2.全局注册: 靠Vue.component('组件名',组件)
三、编写组件标签:
<school></school>
-->
<!-- 准备好一个容器 -->
<div id="root">
<!-- 第三步:编写组件标签 -->
<school></school>
<hr>
<!-- 第三步:编写组件标签 -->
<student></student>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
//第一步:创建school组件
const school = Vue.extend({
// 组件定义时,一定不要写el配置项,因为最终所有的组件都要被一个vm管理,由vm决定服务于哪个容器。
//el: '#root',
template: `
<div>
<h2>学校名称:{{schoolName}}</h2>
<h2>学校地址:{{address}}</h2>
<button @click="showName">点我提示学校名</button>
</div>
`,
data() {
return {
schoolName: '成都大学',
address: '成都'
}
},
methods: {
showName(){
alert(this.schoolName)
}
},
})
//第一步:创建student组件
const student = Vue.extend({
template: `
<div>
<h2>学生姓名:{{studentName}}</h2>
<h2>学校年龄:{{age}}</h2>
</div>
`,
data() {
return {
studentName: 'feng',
age: 18
}
}
})
/* //第一步:创建student组件
const hello =Vue.extend({.....})
//第二步:全局注册组件
Vue.component('hello',hello) */
//创建vm
new Vue({
el: '#root',
//第二步:注册组件(局部注册)
components: {
school, //这个地方简写了(school: school)
student
}
})
//data使用函数式
/* function data(){
return {
a: 1,
b: 2
}
}
const x1 = data()
const x2 = data() */
</script>
</body>
运行效果
2.3 组件的注意点
<body>
<!--
几个注意点:
1.关于组件名:
一个单词组成:
第一种写法(首字母小写): school
第二种写法(首字母大写): School
多个单词组成:
第一种写法(kebab-case命名):my-school
第二种写法(CamelCase命名):MySchool(需要Vue脚手架支持)
备注:
(1).组件名尽可能回避HTML中已有的元素名称,例如:h2、H2都不行。
(2).可以使用name配置项指定组件在开发者工具中呈现的名字。
2.关于组件标签:
第一种写法: <school></school>
第二种写法: <school/>
备注:不用使用脚手架时,<school/>会导致后续组件不能渲染。
3.一个简写方式:
const school = Vue.extend(options)可简写为: const school = options
-->
<!-- 准备好一个容器 -->
<div id="root">
<h1>{{msg}}</h1>
<school></school>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
//定义组件
const school = Vue.extend({
template: `
<div>
<h2>学校名称:{{name}}</h2>
<h2>学校地址:{{address}}</h2>
</div>
`,
data() {
return {
name: '成都大学',
address: '成都'
}
}
})
//注册组件
new Vue({
el: '#root',
data: {
msg: '欢迎学习!'
},
components: {
school,
}
})
</script>
</body>
2.4 组件的嵌套
<body>
<!-- 准备好一个容器 -->
<div id="root">
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
//定义student组件
const student = Vue.extend({
name: 'student',
template: `
<div>
<h2>学生姓名:{{name}}</h2>
<h2>学生年龄:{{age}}</h2>
</div>
`,
data() {
return {
name: 'feng',
age: 18
}
}
})
//定义school组件
const school = Vue.extend({
name: 'school',
template: `
<div>
<h2>学校名称:{{name}}</h2>
<h2>学校地址:{{address}}</h2>
<student></student>
</div>
`,
data() {
return {
name: '成都大学',
address: '成都'
}
},
//注册组件(局部)
components: {
student
}
})
//定义hello组件
const hello = Vue.extend({
template: `<h1>{{msg}}</h1>`,
data(){
return {
msg: '欢迎来到'
}
}
})
//定义app组件
const app = Vue.extend({
template: `
<div>
<hello></hello>
<school></school>
</div>
`,
components: {
school,hello
}
})
//注册组件
new Vue({
template: `<app></app>`,
el: '#root',
//注册组件(局部)
components: {
app
}
})
</script>
</body>
运行结果
2.5 VueComponent构造函数
<body>
<!--
关于VueComponent:
1.school组件本质是一个名为VueComponent的构造函数,且不是程序员定义的,是Vue.extend生成的。
⒉.我们只需要写<school/>或<school></school>,Vue解析时会帮我们创建school组件的实例对象,
即Vue帮我们执行的:new Vuecomponent(options)。
3.特别注意: 每次调用Vue.extend,返回的都是一个全新的VueComponent!!!!
4.关于this指向:
(1).组件配置中:
data函数、methods中的函数、watch中的函数、computed中的函数 它们的this均是【VueComponent实例对象】。
(2).new Vue()配置中:
data函数、methods中的函数、watch中的函数、computed中的函数 它们的this均是【Vue实例对象】。
5.VueComponent的实例对象,以后简称vc(也可称之为:组件实例对象)。
Vue的实例对象,以后简称vm。
-->
<!-- 准备好一个容器 -->
<div id="root">
<school></school>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
//定义school组件
const school = Vue.extend({
name: 'school',
template: `
<div>
<h2>学校名称:{{name}}</h2>
<h2>学校地址:{{address}}</h2>
</div>
`,
data() {
return {
name: '成都大学',
address: '成都'
}
}
})
const vm = new Vue({
el: '#root',
components: {school}
})
</script>
</body>
运行结果
2.6 一个重要内置关系
<body>
<!--
1.一个重要的内置关系:VueComponent.prototype.__proto__ === Vue.prototype
2.为什么要有这个关系: 让组件实例对象(vc)可以访问到 Vue原型上的属性、方法。
-->
<!-- 准备好一个容器 -->
<div id="root">
<school></school> <!-- 创建了vc -->
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
Vue.prototype.x = 99
//定义school组件
const school = Vue.extend({
name: 'school',
template: `
<div>
<h2>学校名称:{{name}}</h2>
<h2>学校地址:{{address}}</h2>
<button @click="showX">点我输出x</button>
</div>
`,
data() {
return {
name: '成都大学',
address: '成都'
}
},
methods: {
showX(){
console.log(this.x)
}
},
})
//创建一个vm
new Vue({
el: '#root',
data: {
msg: 'hello'
},
components: {school}
})
/* //定义一个构造函数
function Demo(){
this.a = 1
this.b = 2
}
//创建一个Demo的实例对象
const d = new Demo()
console.log(Demo.prototype) //显示原型属性
console.log(d.__proto__) //隐式原型属性
console.log(Demo.prototype === d.__proto__)
//程序员通过显示原型属性操作原型对象,追加一个x属性,值为99
Demo.prototype.x = 99
console.log(d.x) */
</script>
</body>
运行结果
2.7 单文件组件
目录结构
School.vue
<template>
<!-- 组件的结构 -->
<div class="demo">
<h2>学校名称:{{name}}</h2>
<h2>学校地址:{{address}}</h2>
<button @click="showX">点我输出x</button>
</div>
</template>
<script>
//组件交互相关的代码(数据、方法等等)
/* const school = Vue.extend({
data() {
return {
name: '成都大学',
address: '成都'
}
},
methods: {
showX(){
console.log(this.x)
}
},
})
export default school //默认暴露 */
//简写
export default {
name: 'School',
data() {
return {
name: '成都大学',
address: '成都'
}
},
methods: {
showX(){
console.log(this.x)
}
},
}
</script>
<style>
/* 组件的样式 */
.demo {
background-color: orange;
}
</style>
Student.vue
<template>
<div>
<h2>学生姓名:{{name}}</h2>
<h2>学生年龄:{{age}}</h2>
</div>
</template>
<script>
export default {
name: 'Student',
data() {
return {
name: 'feng',
age: 18
}
}
}
</script>
App.vue
<template >
<div>
<School></School>
<Student></Student>
</div>
</template>
<script>
import School from './School.vue'
import Student from './Student.vue'
export default {
name: 'App',
components: {
School,
Student
}
}
</script>
main.js
import App from '/App.vue'
new Vue({
el: '#root',
components: {
App
}
})
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- 准备好一个容器 -->
<div id="root">
<App></App>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript" src="./main.js"></script>
</body>
</html>
浏览器不能直接运行,需要在脚手架中运行。
3 Vue脚手架
3.1 安装
前提:安装nodejs
备注:
配置淘宝镜像(防止出现下载缓慢)
cmd 运行 npm config set registry https://registry.npm.taobao.org
具体步骤:
1、第一步(仅第一次执行): 全局安装@vue/cli
npm install -g @vue/cli
2、第二步:切换到你要创建项目的目录,然后使用命令创建项目
vue create xxxx
3、第三步:启动项目
npm run serve
创建成功
3.2 分析脚手架结构
运行之前写的项目
App.vue
<template >
<div>
<img src="./assets/logo.png" alt="logo">
<School></School>
<Student></Student>
</div>
</template>
<script>
import School from './components/School.vue'
import Student from './components/Student.vue'
export default {
name: 'App',
components: {
School,
Student
}
}
</script>
main.js
/*
该文件是整个项目的入口文件
*/
//引入Vue
import Vue from 'vue'
//引入App组件,它是所有组件的父组件
import App from './App.vue'
//关闭vue的生产提示
Vue.config.productionTip = false
//创建Vue实例对象 ---vm
new Vue({
el: '#app',
//完成了这个功能:将App组件放入容器中
render: h => h(App),
})
index.html
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<!-- 针对IE浏览器的一个特殊配置,含义是让IE浏览器以最高的渲染级别渲染页面 -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- 开启移动端的理想视口 -->
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<!-- 配置页签图标 -->
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<!-- 配置网页标题 -->
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<!-- 当浏览器不支持js时noscript中的元素就会被渲染 -->
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<!-- 容器 -->
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
终端运行:npm run serve
如果报名称异常,关闭语法检查。
运行效果
3.3 render 函数
main.js
/*
该文件是整个项目的入口文件
*/
//引入Vue
import Vue from 'vue'
//引入App组件,它是所有组件的父组件
import App from './App.vue'
//关闭vue的生产提示
Vue.config.productionTip = false
/*
关于不同版本的Vue:
1.vue.js 与vue.runtime.xxx.js的区别:
(1).vue.js是完整版的Vue,包含:核心功能+模板解析器。
(2) .vue.runtime.xxx.js是运行版的Vue,只包含: 核心功能; 没有模板解析器。
2.因为vue.runtime.xxx.js没有模板解析器,所以不能使用template配置项,
需要使用render函数接收到的createElement函数去指定具体内容。
*/
//创建Vue实例对象 ---vm
new Vue({
el: '#app',
//完成了这个功能:将App组件放入容器中
render: h => h(App),//App不能带引号,带了引号表示html中有app元素,直接写App变量
/*
解释:render
因为这个地方引入的是残缺的vue,没有模板解析器,所以不能使用template标签
只能使用:
render(createElement){
return createElement('h1','你好啊')
}
这个方法中没有用this,所以可以用箭头函数
简写为:render: p => p('h1','你好啊'),
*/
/* template: `<h1>你好啊</h1>`,
components: {App} */
})
总结
3.4 ref
App.vue
<template>
<div>
<h1 v-text="msg" ref="title"></h1>
<button ref="btn"@click="showDOM">点我输出上方的DOM元素</button>
<School ref="sch"/>
</div>
</template>
<script>
//引入School组件
import School from './components/School'
export default {
name: 'App',
data() {
return {
msg: '欢迎学习Vue'
}
},
components: {School},
methods: {
showDOM(){
console.log(this.$refs.title) //真实的DOM元素
console.log(this.$refs.btn) //真实的DOM元素
console.log(this.$refs.sch) //School组件的实例对象(vc)
}
},
}
</script>
<style lang="">
</style>
运行结果
总结
3.5 props
Student.vue
<template lang="">
<div class="student">
<h1>{{msg}}</h1>
<h2>学生姓名:{{name}}</h2>
<h2>学生性别:{{sex}}</h2>
<h2>学生年龄:{{myAge}}</h2>
<button @click="updateAge">尝试修改收到的年龄</button>
</div>
</template>
<script>
export default {
name: 'Student',
data() {
return {
msg: 'I am a student',
myAge:this.age
}
},
methods: {
updateAge(){
this.myAge++
}
},
props: ['name','age','sex'] //简单声明接收
//接收的同时对数据进行类型限制
/* props:{
name: String,
age: Number,
sex: String
} */
//接收的同时对数据:进行类型限制+默认值的指定+必要性的限制
/* props:{
name:{
type:String, //name的类型是字符串
required:true //name是必要的
},
age:{
type:Number,
default:99 //默认值
},
sex:{
type:String,
required:true
}
} */
}
</script>
App.vue
<template>
<div>
<Student name="feng" sex="男" :age="18"/>
</div>
</template>
<script>
//引入School组件
import Student from './components/Student'
export default {
name: 'App',
components: {Student},
}
</script>
<style lang="">
</style>
运行结果
总结
3.6 mixin
mixin.js
export const mixin = {
methods: {
showName(){
alert(this.name)
}
},
}
Student.vue
<template lang="">
<div class="student">
<h2 @click="showName">学生姓名:{{name}}</h2>
<h2>学生性别:{{sex}}</h2>
</div>
</template>
<script>
// import {mixin} from '../mixin.js'
export default {
name: 'Student',
data() {
return {
name: 'feng',
sex:'男'
}
},
// mixins:[mixin]
}
</script>
School.vue
<template lang="">
<div >
<h2 @click="showName">学校名称:{{name}}</h2>
<h2>学校地址:{{address}}</h2>
</div>
</template>
<script>
//引入一个混合
// import {mixin} from '../mixin.js'
export default {
name: 'School',
data() {
return {
name: '成都大学',
address:'成都'
}
},
// mixins:[mixin]
}
</script>
main.js
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
import { mixin } from './mixin'
//关闭Vue的生产提示
Vue.config.productionTip = false
Vue.mixin(mixin)
//创建vm
new Vue({
el: '#app',
render: h => h(App)
})
运行结果
总结
3.7 插件
plugins.js
export default {
install(Vue,x,y,z){
console.log(x,y,z)
//全局过滤器
Vue.filter('mySlice',function(value){
return value.slice(0,5)
})
//定义全局指令
Vue.directive('fbind',{
//指令与元素成功绑定时(一上来)
bind(element,binding){
element.value = binding.value
},
//指定所在元素被插入页面时
inserted(element,binding){
element.focus()
},
//指令所在的模板被重新解析时
update(element,binding){
element.value = binding.value
}
})
//定义混入
Vue.mixin({
data() {
return {
x:100,
y:200
}
},
})
//给Vue原型上添加一个方法(vm和vc就都能用了)
Vue.prototype.hello = () =>{alert('hello')}
}
}
main.js
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入插件
import plugins from './plugins'
//关闭Vue的生产提示
Vue.config.productionTip = false
//应用(使用)插件
Vue.use(plugins,1,2,3)
//创建vm
new Vue({
el: '#app',
render: h => h(App)
})
Student.vue
<template lang="">
<div class="student">
<h2>学生姓名:{{name}}</h2>
<h2>学生性别:{{sex}}</h2>
<input type="text" v-fbind:value="name">
</div>
</template>
<script>
export default {
name: 'Student',
data() {
return {
name: 'feng',
sex:'男'
}
},
}
</script>
School.vue
<template lang="">
<div >
<h2>学校名称:{{name | mySlice}}</h2>
<h2>学校地址:{{address}}</h2>
<button @click="test">点我测试一下hello方法</button>
</div>
</template>
<script>
export default {
name: 'School',
data() {
return {
name: '成都大学chengdu',
address:'成都'
}
},
methods: {
test(){
this.hello()
}
},
}
</script>
运行结果
总结
3.8 scoped
School.vue
<template lang="">
<div class="demo">
<h2>学校名称:{{name}}</h2>
<h2>学校地址:{{address}}</h2>
</div>
</template>
<script>
export default {
name: 'School',
data() {
return {
name: '成都大学chengdu',
address:'成都'
}
},
}
</script>
<style scoped>
.demo{
background-color: skyblue;
}
</style>
安装less
npm i less-loader@7
Student.vue
<template lang="">
<div class="demo">
<h2>学生姓名:{{name}}</h2>
<h2 class="qwe">学生性别:{{sex}}</h2>
</div>
</template>
<script>
export default {
name: 'Student',
data() {
return {
name: 'feng',
sex:'男'
}
},
}
</script>
<style lang="less" scoped>
.demo{
background-color: pink;
.qwe{
font-size: 40px;
}
}
</style>
运行结果
总结
3.9 Todo-list案例
组件化编码流程(通用)
1.实现静态组件:抽取组件,使用组件实现静态页面效果
2.展示动态数据:
2.1 数据的类型、名称是什么?
2.2 数据保存在哪个组件?
3.交互--从绑定事件监听开始
生成一个nanoid(类似uuid的简化)
npm i nanoid
App.vue
<template>
<div class="todo-container">
<div class="todo-wrap">
<MyHeader :addTodo="addTodo"/>
<MyList :todos="todos" :checkTodo="checkTodo" :deleteTodo="deleteTodo"/>
<MyFooter :todos="todos" :checkAllTodo="checkAllTodo" :clearAllTodo="clearAllTodo"/>
</div>
</div>
</template>
<script>
import MyFooter from './components/MyFooter'
import MyHeader from './components/MyHeader'
import MyList from './components/MyList'
export default {
name: 'App',
components: {MyFooter,MyHeader,MyList},
data() {
return {
todos:[
{id:'001',title:'抽烟',done:true},
{id:'002',title:'喝酒',done:false},
{id:'003',title:'开车',done:true},
]
}
},
methods: {
//添加一个todo
addTodo(todoObj){
this.todos.unshift(todoObj)
},
//勾选or取消勾选一个todo
checkTodo(id){
this.todos.forEach((todo) => {
if(todo.id === id) todo.done = !todo.done
})
},
//删除一个todo
deleteTodo(id){
this.todos = this.todos.filter((todo) => {
return todo.id !== id
})
},
//全选or取消全选
checkAllTodo(done){
this.todos.forEach(todo => todo.done = done)
},
//清除所有已经完成的todo
clearAllTodo(){
this.todos = this.todos.filter((todo) => !todo.done)
}
},
}
</script>
<style>
/* base */
body {
background-color: #fff;
}
.btn {
display: inline-block;
padding: 4px 12px;
margin-bottom: 0;
font-size: 14px;
line-height: 20px;
text-align: center;
vertical-align: middle;
cursor: pointer;
box-shadow: inset 0 1px 0 rgba(255,255,255,0.2), 0 1px 2px rgba(0, 0,0,0.05);
border-radius: 4px;
}
.btn-danger{
color: #fff;
background-color: #da4f49;
border: 1px solid #bd362f;
}
.btn-danger:hover{
color: #fff;
background-color: #bd362f;
}
.btn:focus{
outline: none;
}
.todo-container{
width: 600px;
margin: 0 auto;
}
.todo-container .todo-wrap{
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
}
</style>
MyHeader.vue
<template>
<div class="todo-header">
<input type="text" placeholder="请输入你的任务名称,按回车键确认" v-model="title" @keyup.enter="add">
</div>
</template>
<script>
import {nanoid} from 'nanoid'
export default {
name:'MyHeader',
props:['addTodo'],
data() {
return {
title:''
}
},
methods: {
add(){
//校验数据
if(!this.title.trim()){
alert('输入不能为空')
return
}
//将用户的输入包装成一个todo对象
const todoObj = {id:nanoid(),title:this.title,done:false}
//通知App组件去添加一个todo对象
this.addTodo(todoObj)
//清空输入
this.title = ''
}
},
}
</script>
<style scoped>
/* header */
.todo-header input{
width: 560px;
height: 28px;
font-size: 14px;
border: 1px solid #ccc;
border-radius: 4px;
padding: 4px 7px;
}
.todo-header input:focus{
outline: none;
border-color: rgba(82,168,236,0.8);
box-shadow: inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);
}
</style>
MyList.vue
<template>
<ul class="todo-main">
<MyItem
v-for="todoObj in todos"
:key="todoObj.id"
:todo="todoObj"
:checkTodo="checkTodo"
:deleteTodo="deleteTodo"
/>
</ul>
</template>
<script>
import MyItem from './MyItem'
export default {
name:'MyList',
components:{MyItem},
props:['todos','checkTodo','deleteTodo']
}
</script>
<style scoped>
/* main */
.todo-main{
margin-left: 0px;
border: 1px solid #ddd;
border-radius: 2px;
padding: 0px;
}
.todo-empty{
height: 40px;
line-height: 40px;
border: 1px solid #ddd;
border-radius: 2px;
padding-left: 5px;
margin-top: 10px;
}
</style>
MyItem.vue
<template>
<li>
<label>
<input type="checkbox" :checked="todo.done" @change="handleCheck(todo.id)"/>
<!-- 如下代码也能实现功能,但是不太推荐,因为有点违法原则,因为修改了props -->
<!-- <input type="checkbox" v-model="todo.done"/> -->
<span>{{todo.title}}</span>
</label>
<button class="btn btn-danger" @click="handleDelete(todo.id)">删除</button>
</li>
</template>
<script>
export default {
name:'MyItem',
//声明接收的todo对象
props:['todo','checkTodo','deleteTodo'],
methods: {
//勾选or取消勾选
handleCheck(id){
//通知App组件将对应的todo对象的done值取反
this.checkTodo(id)
},
//删除
handleDelete(id){
if(confirm('确认删除吗?')){
this.deleteTodo(id)
}
}
},
}
</script>
<style scoped>
/* item */
li {
list-style: none;
height: 36px;
line-height: 36px;
padding: 0 5px;
border-bottom: 1px solid #ddd;
}
li label {
float: left;
cursor: pointer;
}
li label li input {
vertical-align: middle;
margin-right: 6px;
position: relative;
top: -1px;
}
li button {
float: right;
display: none;
margin-top: 3px;
}
li:before {
content: initial;
}
li:last-child {
border-bottom: none;
}
li:hover {
background-color: #ddd;
}
li:hover button {
display: block;
}
</style>
MyFooter.vue
<template>
<div class="todo-footer" v-show="total">
I<label>
<!-- <input type="checkbox" :checked="isAll" @change="checkAll"/> -->
<input type="checkbox" v-model="isAll"/>
</label>
<span>
<span>已完成{{doneTotal}}</span>/ 全部 {{total}}
</span>
<button class="btn btn-danger" @click="clearAll">清除已完成任务</button>
</div>
</template>
<script>
export default {
name:'MyFooter',
props:['todos','checkAllTodo','clearAllTodo'],
computed:{
total(){
return this.todos.length
},
doneTotal(){
/* const x = this.todos.reduce((pre,current) => {
return pre + (current.done ? 1:0)
},0) */
return this.todos.reduce((pre,todo) => pre + (todo.done ? 1:0),0)
},
isAll:{
get(){
return this.doneTotal === this.total && this.total > 0
},
set(value){
this.checkAllTodo(value)
}
}
},
methods: {
/* checkAll(e){
this.checkAllTodo(e.target.checked)
} */
clearAll(){
this.clearAllTodo()
}
},
}
</script>
<style scoped>
/* footer */
.todo-footer {
height: 40px;
line-height: 40px;
padding-left: 6px;
margin-top: 5px;
}
.todo-footer label {
display: inline-block;
margin-right: 20px;
cursor: pointer;
}
.todo-footer label input{
position: relative;
top: -1px;
vertical-align: middle;
margin-right: 5px;
}
.todo-footer button{
float: right;
margin-top: 5px;
}
</style>
总结
4.0 webStorage
localStorage.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2>localStorage</h2>
<button onclick="saveData()">点我保存一个数据</button>
<button onclick="readData()">点我读取一个数据</button>
<button onclick="deleteData()">点我删除一个数据</button>
<button onclick="deleteAllData()">点我清空数据</button>
<script type="text/javascript">
let p = {name:'张三',age:18}
function saveData(){
localStorage.setItem('msg','hello!')
localStorage.setItem('msg2',666)
localStorage.setItem('person',JSON.stringify(p))
}
function readData(){
console.log(localStorage.getItem('msg'))
console.log(localStorage.getItem('msg2'))
const res = localStorage.getItem('person')
console.log(JSON.parse(res))
}
function deleteData(){
localStorage.removeItem('msg2')
}
function deleteAllData(){
localStorage.clear()
}
</script>
</body>
</html>
sessionStorage.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2>sessionStorage</h2>
<button onclick="saveData()">点我保存一个数据</button>
<button onclick="readData()">点我读取一个数据</button>
<button onclick="deleteData()">点我删除一个数据</button>
<button onclick="deleteAllData()">点我清空数据</button>
<script type="text/javascript">
let p = {name:'张三',age:18}
function saveData(){
sessionStorage.setItem('msg','hello!')
sessionStorage.setItem('msg2',666)
sessionStorage.setItem('person',JSON.stringify(p))
}
function readData(){
console.log(sessionStorage.getItem('msg'))
console.log(sessionStorage.getItem('msg2'))
const res = sessionStorage.getItem('person')
console.log(JSON.parse(res))
}
function deleteData(){
sessionStorage.removeItem('msg2')
}
function deleteAllData(){
sessionStorage.clear()
}
</script>
</body>
</html>
运行结果
总结
将Todo-list案例存储到本地
App.vue
<template>
<div class="todo-container">
<div class="todo-wrap">
<MyHeader :addTodo="addTodo"/>
<MyList :todos="todos" :checkTodo="checkTodo" :deleteTodo="deleteTodo"/>
<MyFooter :todos="todos" :checkAllTodo="checkAllTodo" :clearAllTodo="clearAllTodo"/>
</div>
</div>
</template>
<script>
import MyFooter from './components/MyFooter'
import MyHeader from './components/MyHeader'
import MyList from './components/MyList'
export default {
name: 'App',
components: {MyFooter,MyHeader,MyList},
data() {
return {
todos:JSON.parse(localStorage.getItem('todos')) || [] //如果前面是null就使用后面的空数组
}
},
methods: {
//添加一个todo
addTodo(todoObj){
this.todos.unshift(todoObj)
},
//勾选or取消勾选一个todo
checkTodo(id){
this.todos.forEach((todo) => {
if(todo.id === id) todo.done = !todo.done
})
},
//删除一个todo
deleteTodo(id){
this.todos = this.todos.filter((todo) => {
return todo.id !== id
})
},
//全选or取消全选
checkAllTodo(done){
this.todos.forEach(todo => todo.done = done)
},
//清除所有已经完成的todo
clearAllTodo(){
this.todos = this.todos.filter((todo) => !todo.done)
}
},
watch:{
todos:{
deep:true,//开启深度监视,对象中属性值变化也会检测到
handler(value){
localStorage.setItem('todos',JSON.stringify(value))
}
}
}
}
</script>
<style>
/* base */
body {
background-color: #fff;
}
.btn {
display: inline-block;
padding: 4px 12px;
margin-bottom: 0;
font-size: 14px;
line-height: 20px;
text-align: center;
vertical-align: middle;
cursor: pointer;
box-shadow: inset 0 1px 0 rgba(255,255,255,0.2), 0 1px 2px rgba(0, 0,0,0.05);
border-radius: 4px;
}
.btn-danger{
color: #fff;
background-color: #da4f49;
border: 1px solid #bd362f;
}
.btn-danger:hover{
color: #fff;
background-color: #bd362f;
}
.btn:focus{
outline: none;
}
.todo-container{
width: 600px;
margin: 0 auto;
}
.todo-container .todo-wrap{
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
}
</style>
4.1 自定义事件_绑定
Student.vue
<template lang="">
<div class="student">
<h2>学生姓名:{{name}}</h2>
<h2>学生性别:{{sex}}</h2>
<button @click="sendStudentName">把学生名给App</button>
</div>
</template>
<script>
export default {
name: 'Student',
data() {
return {
name: 'feng',
sex:'男'
}
},
methods: {
sendStudentName(){
//触发Student组件实例身上的atguigu事件
this.$emit('atguigu',this.name,666,888)
}
},
}
</script>
<style lang="less" scoped>
.student{
background-color: pink;
padding: 5px;
margin-top: 30px;
}
</style>
App.vue
<template>
<div class="app">
<h1>{{msg}}</h1>
<!-- 通过父组件给子组件传递函数类型的props实现:子给父传递数据 -->
<School :getSchoolName="getSchoolName"/>
<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据( 第一种写法,使用 @ 或 v-on )
atguigu是绑定的事件,getStudentName是触发事件的回调函数-->
<!-- <Student v-on:atguigu="getStudentName"/> -->
<!-- <Student @atguigu="getStudentName"/> 简写形式 -->
<!-- <Student @atguigu.once="getStudentName"/> 只触发一次 -->
<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据( 第二种写法,使用ref ) -->
<Student ref="student"/>
</div>
</template>
<script>
//引入School组件
import Student from './components/Student'
import School from './components/School'
export default {
name: 'App',
components: {School,Student},
data() {
return {
msg:'你好啊!'
}
},
methods: {
getSchoolName(name){
console.log('App收到了学校名:',name)
},
getStudentName(name,...params){//将传递的剩余数据放入params数组中
console.log('App收到了学生名:',name,params) //输出结果:App收到了学生名: feng [666, 888]
}
},
mounted() {
// this.$refs.student.$on('atguigu',this.getStudentName) 绑定自定义事件
this.$refs.student.$once('atguigu',this.getStudentName) //绑定自定义事件(一次性)
},
}
</script>
<style scoped>
.app{
background-color: grey;
padding: 5px;
}
</style>
运行结果
4.2 自定义事件_解绑
App.vue
<template>
<div class="app">
<Student @atguigu="getStudentName" @demo="m1"/> <!-- 简写形式 -->
</div>
</template>
Student.vue
<template lang="">
<div class="student">
<h2>学生姓名:{{name}}</h2>
<h2>学生性别:{{sex}}</h2>
<h2>当前求和为:{{number}}</h2>
<button @click="add">点我number++</button>
<button @click="sendStudentName">把学生名给App</button>
<button @click="unbind">解绑atguigu事件</button>
<button @click="death">销毁当前Student组件的实例(vc)</button>
</div>
</template>
<script>
export default {
name: 'Student',
data() {
return {
name: 'feng',
sex:'男',
number:0
}
},
methods: {
add(){
console.log('add回调被调用了')
this.number++
},
sendStudentName(){
//触发Student组件实例身上的atguigu事件
this.$emit('atguigu',this.name,666,888)
this.$emit('demo')
},
unbind(){
// this.$off('atguigu') //解绑一个自定义事件
this.$off(['atguigu','demo']) //解绑多个自定义事件
// this.$off() //解绑所有的自定义事件
},
death(){
this.$destroy() //销毁了当前Student组件的实例,销毁后所有Student实例的自定义事件全都不奏效。
}
},
}
</script>
<style lang="less" scoped>
.student{
background-color: pink;
padding: 5px;
margin-top: 30px;
}
</style>
运行结果
4.3 自定义事件_总结
4.4 全局事件总线
main.js
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//关闭Vue的生产提示
Vue.config.productionTip = false
const Demo = Vue.extend({})
const d = new Demo()
Vue.prototype.x = d
//创建vm
new Vue({
el: '#app',
render: h => h(App),
beforeCreate(){
Vue.prototype.$bus = this //安装全局事件总线
}
})
App.vue
<template>
<div class="app">
<h1>{{msg}}</h1>
<School/>
<Student/>
</div>
</template>
<script>
//引入School组件
import Student from './components/Student'
import School from './components/School'
export default {
name: 'App',
components: {School,Student},
data() {
return {
msg:'你好啊!',
}
}
}
</script>
<style scoped>
.app{
background-color: grey;
padding: 5px;
}
</style>
School.vue
<template lang="">
<div class="school">
<h2>学校名称:{{name}}</h2>
<h2>学校地址:{{address}}</h2>
</div>
</template>
<script>
export default {
name: 'School',
data() {
return {
name: '成都大学',
address:'成都'
}
},
mounted() {
console.log('School',this.x)
this.$bus.$on('hello',(data) => {
console.log('我是School组件,收到了数据',data)
})
},
beforeDestroy() {
this.$bus.$off('hello')
},
}
</script>
<style scoped>
.school{
background-color: skyblue;
padding: 5px;
}
</style>
Student.vue
<template lang="">
<div class="student">
<h2>学生姓名:{{name}}</h2>
<h2>学生性别:{{sex}}</h2>
<button @click="sendStudentName">把学生名给School组件</button>
</div>
</template>
<script>
export default {
name: 'Student',
data() {
return {
name: 'feng',
sex:'男',
}
},
mounted() {
},
methods: {
sendStudentName(){
this.$bus.$emit('hello',this.name)
}
},
}
</script>
<style lang="less" scoped>
.student{
background-color: pink;
padding: 5px;
margin-top: 30px;
}
</style>
运行结果
个人理解
//main.js
//创建vm
new Vue({
el: '#app',
render: h => h(App),
beforeCreate(){
Vue.prototype.$bus = this //安装全局事件总线
}
})
//这个地方的this就是vm,在钩子beforeCreate()中(这个钩子函数在模板解析之前),将vm赋给Vue原型中的$bus这个傀儡,(vm可以调用$on,$off,$emit,其实vc也可以调用,只是标准方法是使用vm)。之后组件实例对象就可以使用Vue原型中的$bus,调用$on,$off,$emit(原理就是vm和vc都可以访问到Vue原型中的数据)。
//查看2.6中的图片中的标注重要的黄线
4.5 消息订阅与发布
安装pubsub库
npm i pubsub-js
如果版本过高,安装低版本
Student.vue
<template lang="">
<div class="student">
<h2>学生姓名:{{name}}</h2>
<h2>学生性别:{{sex}}</h2>
<button @click="sendStudentName">把学生名给School组件</button>
</div>
</template>
<script>
import pubsub from 'pubsub-js'
export default {
name: 'Student',
data() {
return {
name: 'feng',
sex:'男',
}
},
mounted() {
},
methods: {
sendStudentName(){
pubsub.publish('hello',666)
}
},
}
</script>
<style lang="less" scoped>
.student{
background-color: pink;
padding: 5px;
margin-top: 30px;
}
</style>
School.vue
<template lang="">
<div class="school">
<h2>学校名称:{{name}}</h2>
<h2>学校地址:{{address}}</h2>
</div>
</template>
<script>
import pubsub from 'pubsub-js'
export default {
name: 'School',
data() {
return {
name: '成都大学',
address:'成都'
}
},
mounted() {
this.pubId = pubsub.subscribe('hello',(msgName,data)=>{
console.log('有人发布了hello消息,hello消息的回调执行了',msgName,data)
})
},
beforeDestroy() {
pubsub.unsubscribe(this.pubId) //取消订阅
},
}
</script>
<style scoped>
.school{
background-color: skyblue;
padding: 5px;
}
</style>
运行结果
总结
4.6 $nextTick
<template>
<li>
<label>
<input type="checkbox" :checked="todo.done" @change="handleCheck(todo.id)"/>
<!-- 如下代码也能实现功能,但是不太推荐,因为有点违法原则,因为修改了props -->
<!-- <input type="checkbox" v-model="todo.done"/> -->
<span v-show="!todo.isEdit">{{todo.title}}</span>
<input
v-show="todo.isEdit"
type="text"
:value="todo.title"
@blur="handleBlur(todo,$event)"
ref="inputTitle"
>
</label>
<button class="btn btn-danger" @click="handleDelete(todo.id)">删除</button>
<button v-show="!todo.isEdit" class="btn btn-edit" @click="handleEdit(todo)">编辑</button>
</li>
</template>
<script>
import pubsub from 'pubsub-js'
export default {
name:'MyItem',
//声明接收的todo对象
props:['todo'],
methods: {
//勾选or取消勾选
handleCheck(id){
//通知App组件将对应的todo对象的done值取反
// this.checkTodo(id)
this.$bus.$emit('checkTodo',id)
},
//删除
handleDelete(id){
if(confirm('确认删除吗?')){
// this.deleteTodo(id)
// this.$bus.$emit('deleteTodo',id)
pubsub.publish('deleteTodo',id)
}
},
//编辑
handleEdit(todo){
//判断是否有属性
if(todo.hasOwnProperty('isEdit')){
todo.isEdit = true
}else{
this.$set(todo,'isEdit',true)
}
//下一次DOM更新结束后执行
this.$nextTick(function(){
this.$refs.inputTitle.focus() //13行
})
},
//失去焦点回调(真正执行修改逻辑)
handleBlur(todo,e){
todo.isEdit = false
if(!e.target.value.trim()){
alert('输入不能为空')
return
}
this.$bus.$emit('updateTodo',todo.id,e.target.value)
}
},
}
</script>
运行效果
4.7 动画效果
Test.vue
<template>
<div>
<button @click="isShow = !isShow">显示/隐藏</button>
<transition name="hello" appear>
<h1 v-show="isShow">你好啊!</h1>
</transition>
</div>
</template>
<script>
export default {
name:'Test',
data() {
return {
isShow:true
}
},
}
</script>
<style scoped>
h1{
background-color: orange;
}
//起始过程中效果
.hello-enter-active{
animation: feng 0.5s linear;
}
.hello-leave-active{
animation: feng 0.5s linear reverse;//0.5s,连贯,反转
}
//起始位置
@keyframes feng{
from{
transform: translateX(-100%);
}
to{
transform: translateX(0px);
}
}
</style>
4.8 过度效果
App.vue
<template>
<div >
<Test/>
<Test2/>
</div>
</template>
<script>
import Test from './components/Test'
import Test2 from './components/Test2'
export default {
name: 'App',
components: {Test,Test2},
}
</script>
Test2.vue
<template>
<div>
<button @click="isShow = !isShow">显示/隐藏</button>
<transition name="hello" appear>
<h1 v-show="isShow">你好啊!</h1>
</transition>
</div>
</template>
<script>
export default {
name:'Test2',
data() {
return {
isShow:true
}
},
}
</script>
<style scoped>
h1{
background-color: orange;
}
/* 进入的起点 ,离开的终点*/
.hello-enter,.hello-leave-to{
transform: translateX(-100%);
}
.hello-enter-active,.hello-leave-active{
transition: 0.5s linear;
}
/* 进入的终点,离开的起点 */
.hello-enter-to, .hello-leave{
transform: translateX(0);
}
</style>
运行效果
4.9 多个元素过度
<template>
<div>
<button @click="isShow = !isShow">显示/隐藏</button>
<transition-group name="hello" appear>
<h1 v-show="!isShow" key="1">你好啊!</h1>
<h1 v-show="isShow" key="2">feng!</h1>
</transition-group>
</div>
</template>
<script>
export default {
name:'Test2',
data() {
return {
isShow:true
}
},
}
</script>
<style scoped>
h1{
background-color: orange;
}
/* 进入的起点 ,离开的起点*/
.hello-enter,.hello-leave-to{
transform: translateX(-100%);
}
.hello-enter-active,.hello-leave-active{
transition: 0.5s linear;
}
/* 进入的终点,离开的终点 */
.hello-enter-to, .hello-leave{
transform: translateX(0);
}
</style>
运行效果
5.0 集成第三方动画
安装: npm install animate.css
Test3.vue
<template>
<div>
<button @click="isShow = !isShow">显示/隐藏</button>
<transition-group
appear
name="animate__animated animate__bounce" //查看官网
enter-active-class="animate__swing"
leave-active-class="animate__backOutUp"
>
<h1 v-show="!isShow" key="1">你好啊!</h1>
<h1 v-show="isShow" key="2">feng!</h1>
</transition-group>
</div>
</template>
<script>
import 'animate.css'
export default {
name:'Test3',
data() {
return {
isShow:true
}
},
}
</script>
<style scoped>
h1{
background-color: orange;
}
</style>
运行效果
5.1 总结过度与动画
4 Vue中的ajax
4.1 配置代理
方式一
安装axios : npm i axios
vue.config.js
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
lintOnSave: false, //关闭语法检查
//开启代理服务器,代理服务器端口还是8080,这个5000代表请求服务器的端口
devServer:{
proxy: 'http://localhost:5000'
}
})
App.vue
<template>
<div >
<button @click="getStudents">获取学生信息</button>
</div>
</template>
<script>
export default {
name:'App',
methods: {
getStudents(){
//这个地方是代理服务器的端口,和本地服务器端口是一样的
axios.get('http://localhost:8080/students').then(
response => {
console.log('请求成功了',response.data)
},
error => {
console.log('请求失败了',error.message)
}
)
}
},
}
</script>
缺点:
1、只能配置一个请求服务器
2、不能完全控制是否能走代理服务器,然后通过代理服务器到请求的服务器。如果public文件夹中存在对应的路径,则直接走public中的路径。
总结:
方式二
vue.config.js
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
lintOnSave: false, //关闭语法检查
//开启代理服务器(方式一)
/* devServer:{
proxy: 'http://localhost:5000'
}, */
//开启代理服务器(方式二)
devServer: {
proxy: {
'/api':{
target: 'http://localhost:5000',
pathRewrite:{'^/api':''},
// ws: true, //用于支持websocket
// changeOrigin: true //用于控制请求头中的host值(是否撒谎)
},
'/demo':{
target: 'http://localhost:5001',
pathRewrite:{'^/demo':''},
// ws: true, //用于支持websocket
// changeOrigin: true //用于控制请求头中的host值(是否撒谎)
}
}
}
})
App.vue
<template>
<div >
<button @click="getStudents">获取学生信息</button>
<button @click="getCars">获取汽车信息</button>
</div>
</template>
<script>
export default {
name:'App',
methods: {
getStudents(){
axios.get('http://localhost:8080/api/students').then(
response => {
console.log('请求成功了',response.data)
},
error => {
console.log('请求失败了',error.message)
}
)
},
getCars(){
axios.get('http://localhost:8080/demo/cars').then(
response => {
console.log('请求成功了',response.data)
},
error => {
console.log('请求失败了',error.message)
}
)
}
},
}
</script>
总结:
4.2 vue-resource
安装:npm i vue-resource
main.js
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入插件
import vueResource from 'vue-resource'
//关闭Vue的生产提示
Vue.config.productionTip = false
//使用插件
Vue.use(vueResource)
//创建vm
new Vue({
el: '#app',
render: h => h(App),
beforeCreate() {
Vue.prototype.$bus = this
},
})
Search.vue
<template>
<section class="jumbotron">
<h3 class="jumbotron-heading">Search Github Users</h3>
<div>
<input type="text" v-model="keyWord" placeholder="输入name进行搜索"/>
<button @click="searchUsers">Search Users</button>
</div>
</section>
</template>
<script>
export default {
name:'Search',
data() {
return {
keyWord:''
}
},
methods: {
searchUsers(){
//请求前更新List的数据
this.$bus.$emit('updateListData',{isFirst:false,isLoading:true,errMsg:'',users:[]})
this.$http.get(`https://api.github.com/search/users?q=${this.keyWord}`).then(
response => {
//请求成功后更新List的数据
this.$bus.$emit('updateListData',{isLoading:false,errMsg:'',users:response.data.items})
},
error => {
//请求失败后更新List的数据
this.$bus.$emit('updateListData',{isLoading:false,errMsg:error.message,users:[]})
}
)
}
},
}
</script>
<style>
</style>
4.3 默认插槽
Category.vue
<template>
<div class="category">
<h3>{{title}}分类</h3>
<!-- 定义一个插槽(挖个坑,等着组件的使用者进行填充) -->
<slot>我是一些默认值,当使用者没有传递具体结构时,我会出现</slot>
</div>
</template>
<script>
export default {
name:'Category',
props:['title']
}
</script>
<style>
.category{
background-color: skyblue;
width: 200px;
height: 300px;
}
h3{
background-color: orange;
text-align: center;
}
</style>
App.vue
<template>
<div class="container">
<Category title="美食">
<img src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg" alt="">
</Category>
<Category title="游戏">
<ul>
<li v-for="(g, index) in games" :key="index">{{g}}</li>
</ul>
</Category>
<Category title="电影">
<video controls src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"></video>
</Category>
</div>
</template>
<script>
import Category from './components/Category'
export default {
name:'App',
components:{Category},
data() {
return {
foods:['火锅','烧烤','小龙虾','牛排'],
games:['红色警戒','穿越火线',"劲舞团",'超级玛丽'],
films:['《教父》','《拆弹专家》','《你好,李焕英》','《尚硅谷》']
}
},
}
</script>
<style>
.container{
display: flex;
justify-content: space-around;
}
video{
width: 100%;
}
img{
width: 100%;
}
</style>
运行效果
4.3 具名插槽
Category.vue
<template>
<div class="category">
<h3>{{title}}分类</h3>
<!-- 定义一个插槽(挖个坑,等着组件的使用者进行填充) -->
<slot name="center">我是一些默认值,当使用者没有传递具体结构时,我会出现1</slot>
<slot name="footer">我是一些默认值,当使用者没有传递具体结构时,我会出现2</slot>
</div>
</template>
<script>
export default {
name:'Category',
props:['title']
}
</script>
<style>
.category{
background-color: skyblue;
width: 200px;
height: 300px;
}
h3{
background-color: orange;
text-align: center;
}
</style>
App.vue
<template>
<div class="container">
<Category title="美食">
<img slot="center" src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg" alt="">
<a slot="footer" href="http://www.baidu.com">更多美食</a>
</Category>
<Category title="游戏">
<ul slot="center">
<li v-for="(g, index) in games" :key="index">{{g}}</li>
</ul>
<div class="foot" slot="footer">
<a href="http://www.baidu.com">单机游戏</a>
<a href="http://www.baidu.com">网络游戏</a>
</div>
</Category>
<Category title="电影">
<video slot="center" src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"></video>
<template v-slot:footer>
<div class="foot">
<a href="http://www.baidu.com">经典</a>
<a href="http://www.baidu.com">热门</a>
<a href="http://www.baidu.com">推荐</a>
</div>
<h4>欢迎前来观影</h4>
</template>
</Category>
</div>
</template>
<script>
import Category from './components/Category'
export default {
name:'App',
components:{Category},
data() {
return {
foods:['火锅','烧烤','小龙虾','牛排'],
games:['红色警戒','穿越火线',"劲舞团",'超级玛丽'],
films:['《教父》','《拆弹专家》','《你好,李焕英》','《尚硅谷》']
}
},
}
</script>
<style>
.container,.foot{
display: flex;
justify-content: space-around;
}
video{
width: 100%;
}
img{
width: 100%;
}
h4{
text-align: center;
}
</style>
运行效果
4.4 作用域插槽
Category.vue
<template>
<div class="category">
<h3>{{title}}分类</h3>
<slot :games="games">我是默认的一些内容</slot>
</div>
</template>
<script>
export default {
name:'Category',
props:['title'],
data() {
return {
games:['红色警戒','穿越火线',"劲舞团",'超级玛丽'],
}
},
}
</script>
<style>
.category{
background-color: skyblue;
width: 200px;
height: 300px;
}
h3{
background-color: orange;
text-align: center;
}
</style>
App.vue
<template>
<div class="container">
<Category title="游戏">
<template scope="feng">
<ul>
<li v-for="(g, index) in feng.games" :key="index">{{g}}</li>
</ul>
</template>
</Category>
<Category title="游戏">
<template scope="{games}">
<ol>
<li style="color: red;" v-for="(g, index) in games" :key="index">{{g}}</li>
</ol>
</template>
</Category>
<Category title="游戏">
<template slot-scope="{games}">
<h4 v-for="(g, index) in games" :key="index">{{g}}</h4>
</template>
</Category>
</div>
</template>
<script>
import Category from './components/Category'
export default {
name:'App',
components:{Category},
}
</script>
<style>
.container,.foot{
display: flex;
justify-content: space-around;
}
video{
width: 100%;
}
img{
width: 100%;
}
h4{
text-align: center;
}
</style>
总结:
5 vuex
5.1 理解
概念:
专门在 Vue中实现集中式状态(数据)管理的一个Vue插件,对vue应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方式,且适用于任意组件间通信。
什么时候用vuex?
1、多个组件依赖于同—状态
2、来自不同组件的行为需要变更同一状态
原理图
5.2 安装与使用
安装
npm i vuex@3
main.js
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入插件
import vueResource from 'vue-resource'
//引入store
import store from './store'
//关闭Vue的生产提示
Vue.config.productionTip = false
//使用插件
Vue.use(vueResource)
//创建vm
new Vue({
el: '#app',
render: h => h(App),
store,
beforeCreate() {
Vue.prototype.$bus = this
},
})
App.vue
<template>
<Count/>
</template>
<script>
import Count from './components/Count'
export default {
name:'App',
components:{Count},
}
</script>
Count.vue
<template>
<div>
<h1>当前求和为:{{$store.state.sum}}</h1>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="increament">+</button>
<button @click="decreament">-</button>
<button @click="increamentOdd">当前求和为奇数再加</button>
<button @click="increamentWait">等一等再加</button>
</div>
</template>
<script>
export default {
name:'Count',
data() {
return {
n:1,//用户选择的数字
}
},
methods: {
increament(){
this.$store.commit('ADD',this.n)
},
decreament(){
this.$store.commit('JIAN',this.n)
},
increamentOdd(){
this.$store.dispatch('addOdd',this.n)
},
increamentWait(){
this.$store.dispatch('addWait',this.n)
},
},
}
</script>
<style>
button{
margin-left: 5px;
}
</style>
index.js
//该文件用于创建Vuex中最为核心的store
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//应用Vuex插件
Vue.use(Vuex)
//准备actions——用于响应组件中的动作
const actions = {
/* add(context,value){
context.commit('ADD',value)
},
jian(context,value){
context.commit('JIAN',value)
}, */
addOdd(context,value){
if(context.state.sum % 2){
context.commit('ADD',value)
}
},
addWait(context,value){
setTimeout(() => {
context.commit('ADD',value)
}, 500);
}
}
//准备mutations——用于操作数据(state)
const mutations = {
ADD(state,value){
state.sum += value
},
JIAN(state,value){
state.sum -= value
}
}
//准备state——用于存储数据
const state = {
sum:0 //当前的和
}
//创建并暴露store
export default new Vuex.Store({
actions,mutations,state,
})
运行效果
总结:
5.3 getters
Count.vue
<template>
<div>
<h1>当前求和为:{{$store.state.sum}}</h1>
<h2>当前求和放大10倍为:{{$store.getters.bigSum}}</h2>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="increament">+</button>
<button @click="decreament">-</button>
<button @click="increamentOdd">当前求和为奇数再加</button>
<button @click="increamentWait">等一等再加</button>
</div>
</template>
<script>
export default {
name:'Count',
data() {
return {
n:1,//用户选择的数字
}
},
methods: {
increament(){
this.$store.commit('ADD',this.n)
},
decreament(){
this.$store.commit('JIAN',this.n)
},
increamentOdd(){
this.$store.dispatch('addOdd',this.n)
},
increamentWait(){
this.$store.dispatch('addWait',this.n)
},
},
}
</script>
<style>
button{
margin-left: 5px;
}
</style>
index.js
//该文件用于创建Vuex中最为核心的store
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//应用Vuex插件
Vue.use(Vuex)
//准备actions——用于响应组件中的动作
const actions = {
/* add(context,value){
context.commit('ADD',value)
},
jian(context,value){
context.commit('JIAN',value)
}, */
addOdd(context,value){
if(context.state.sum % 2){
context.commit('ADD',value)
}
},
addWait(context,value){
setTimeout(() => {
context.commit('ADD',value)
}, 500);
}
}
//准备mutations——用于操作数据(state)
const mutations = {
ADD(state,value){
state.sum += value
},
JIAN(state,value){
state.sum -= value
}
}
//准备state——用于存储数据
const state = {
sum:0 //当前的和
}
//准备getters——用于将state中的数据进行加工
const getters = {
bigSum(state){
return state.sum * 10
}
}
//创建并暴露store
export default new Vuex.Store({
actions,mutations,state,getters
})
运行效果
5.4 四个map方法的使用
Count.vue
<template>
<div>
<h1>当前求和为:{{sum}}</h1>
<h2>当前求和放大10倍为:{{bigSum}}</h2>
<h2>我在{{school}},学习{{subject}}</h2>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="increament">+</button>
<button @click="decreament">-</button>
<button @click="increamentOdd">当前求和为奇数再加</button>
<button @click="increamentWait">等一等再加</button>
</div>
</template>
<script>
import {mapState,mapGetters} from 'vuex'
export default {
name:'Count',
data() {
return {
n:1,//用户选择的数字
}
},
computed:{
//靠程序员自己亲自去写计算属性
/* sum(){
return this.$store.state.sum
},
school(){
return this.$store.getters.school
},
subject(){
return this.$store.getters.subject
}, */
/* mapState返回的是一个对象,对象里面:he是k, v是一个function。 ... 语法是将对象中的所有k,v放入到外面的对象中 */
//借助mapState生成计算属性,从state中读取数据。(对象写法)
// ...mapState({he:'sum',xuexiao:'school',xueke:'subject'}),
/* 直接使用对象的简写方式有误,{sum} => {sum:sum} 有误,所以这个地方使用数组形式 */
// 借助mapState生成计算属性,从state中读取数据。(数组写法)
...mapState(['sum','school','subject']),
/* --------------------------------------- */
/* bigSum(){
return this.$store.getters.bigSum
} */
//借助mapGetters生成计算属性,从getters中读取数据。(对象写法)
...mapGetters({bigSum:'bigSum'}),
//借助mapGetters生成计算属性,从getters中读取数据。(数组写法)
...mapGetters(['bigSum'])
},
methods: {
increament(){
this.$store.commit('ADD',this.n)
},
decreament(){
this.$store.commit('JIAN',this.n)
},
increamentOdd(){
this.$store.dispatch('addOdd',this.n)
},
increamentWait(){
this.$store.dispatch('addWait',this.n)
},
},
}
</script>
<style>
button{
margin-left: 5px;
}
</style>
运行效果
Count.vue
<template>
<div>
<h1>当前求和为:{{sum}}</h1>
<h2>当前求和放大10倍为:{{bigSum}}</h2>
<h2>我在{{school}},学习{{subject}}</h2>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="increament(n)">+</button>
<button @click="decreament(n)">-</button>
<button @click="increamentOdd(n)">当前求和为奇数再加</button>
<button @click="increamentWait(n)">等一等再加</button>
</div>
</template>
<script>
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
export default {
name:'Count',
data() {
return {
n:1,//用户选择的 数字
}
},
computed:{
/* mapState返回的是一个对象,对象里面:he是k, v是一个function。 ... 语法是将对象中的所有k,v放入到外面的对象中 */
//借助mapState生成计算属性,从state中读取数据。(对象写法)
// ...mapState({he:'sum',xuexiao:'school',xueke:'subject'}),
/* 直接使用对象的简写方式有误,{sum} => {sum:sum} 有误,所以这个地方使用数组形式 */
// 借助mapState生成计算属性,从state中读取数据。(数组写法)
...mapState(['sum','school','subject']),
/* --------------------------------------- */
//借助mapGetters生成计算属性,从getters中读取数据。(对象写法)
...mapGetters({bigSum:'bigSum'}),
//借助mapGetters生成计算属性,从getters中读取数据。(数组写法)
...mapGetters(['bigSum'])
},
methods: {
//程序员亲自写方法
/* increament(){
this.$store.commit('ADD',this.n)
},
decreament(){
this.$store.commit('JIAN',this.n)
}, */
//借助mapMutations生成对应的方法,方法中会调用commit去联系mutations(对象写法)
...mapMutations({increament:'ADD',decreament:'JIAN'}),
//借助mapMutations生成对应的方法,方法中会调用commit去联系mutations(数组写法)
// ...mapMutations(['ADD','JIAN']),
/* ----------------------------------------- */
//程序员亲自写方法
/* increamentOdd(){
this.$store.dispatch('addOdd',this.n)
},
increamentWait(){
this.$store.dispatch('addWait',this.n)
}, */
//借助mapActions生成对应的方法,方法中会调用dispatch去联系action(对象写法)
...mapActions({increamentOdd:'addOdd',increamentWait:'addWait'}),
//借助mapActions生成对应的方法,方法中会调用dispatch去联系action(数组写法)
// ...mapActions(['addOdd','addWait'])
},
}
</script>
<style>
button{
margin-left: 5px;
}
</style>
运行效果
5.5 多组件共享数据
main.js
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入插件
import vueResource from 'vue-resource'
//引入store
import store from './store'
//关闭Vue的生产提示
Vue.config.productionTip = false
//使用插件
Vue.use(vueResource)
//创建vm
new Vue({
el: '#app',
render: h => h(App),
store,
beforeCreate() {
Vue.prototype.$bus = this
},
})
App.vue
<template>
<div>
<Count/>
<hr>
<Person/>
</div>
</template>
<script>
import Count from './components/Count'
import Person from './components/Person'
export default {
name:'App',
components:{Count,Person},
}
</script>
index.js
//该文件用于创建Vuex中最为核心的store
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//应用Vuex插件
Vue.use(Vuex)
//准备actions——用于响应组件中的动作
const actions = {
/* add(context,value){
context.commit('ADD',value)
},
jian(context,value){
context.commit('JIAN',value)
}, */
addOdd(context,value){
if(context.state.sum % 2){
context.commit('ADD',value)
}
},
addWait(context,value){
setTimeout(() => {
context.commit('ADD',value)
}, 500);
}
}
//准备mutations——用于操作数据(state)
const mutations = {
ADD(state,value){
console.log('mutations中的ADD被调用了')
state.sum += value
},
JIAN(state,value){
console.log('mutations中的JIAN被调用了')
state.sum -= value
},
ADD_PERSON(state,value){
console.log('mutations中的ADD_PERSON被调用了')
state.personList.unshift(value)
}
}
//准备state——用于存储数据
const state = {
sum:0, //当前的和
school:'成都大学',
subject:'前端',
personList:[
{id:'001',name:'张三'}
]
}
//准备getters——用于将state中的数据进行加工
const getters = {
bigSum(state){
return state.sum * 10
}
}
//创建并暴露store
export default new Vuex.Store({
actions,mutations,state,getters
})
Count.vue
<template>
<div>
<h1>当前求和为:{{sum}}</h1>
<h2>当前求和放大10倍为:{{bigSum}}</h2>
<h2>我在{{school}},学习{{subject}}</h2>
<h3 style="color: red;">Person组件的总人数是:{{personList.length}}</h3>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="increament(n)">+</button>
<button @click="decreament(n)">-</button>
<button @click="increamentOdd(n)">当前求和为奇数再加</button>
<button @click="increamentWait(n)">等一等再加</button>
</div>
</template>
<script>
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
export default {
name:'Count',
data() {
return {
n:1,//用户选择的 数字
}
},
computed:{
// 借助mapState生成计算属性,从state中读取数据。(数组写法)
...mapState(['sum','school','subject','personList']),
//借助mapGetters生成计算属性,从getters中读取数据。(对象写法)
...mapGetters({bigSum:'bigSum'}),
},
methods: {
//借助mapMutations生成对应的方法,方法中会调用commit去联系mutations(对象写法)
...mapMutations({increament:'ADD',decreament:'JIAN'}),
//借助mapActions生成对应的方法,方法中会调用dispatch去联系action(对象写法)
...mapActions({increamentOdd:'addOdd',increamentWait:'addWait'}),
},
}
</script>
<style>
button{
margin-left: 5px;
}
</style>
Person.vue
<template>
<div>
<h1>人员列表</h1>
<h3 style="color: red;">Count组件求和为:{{sum}}</h3>
<input type="text" placeholder="请输入名字" v-model="name">
<button @click="add">添加</button>
<ul>
<li v-for="(p, index) in personList" :key="index">{{p.name}}</li>
</ul>
</div>
</template>
<script>
import {nanoid} from 'nanoid'
export default {
name:'Person',
data() {
return {
name:'',
}
},
computed:{
personList(){
return this.$store.state.personList
},
sum(){
return this.$store.state.sum
}
},
methods: {
add(){
const personObj = {id:nanoid(),name:this.name}
this.$store.commit('ADD_PERSON',personObj)
this.name = ''
}
},
}
</script>
<style>
</style>
运行效果
5.6 模块化+命名空间
main.js
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入插件
import vueResource from 'vue-resource'
//引入store
import store from './store'
//关闭Vue的生产提示
Vue.config.productionTip = false
//使用插件
Vue.use(vueResource)
//创建vm
new Vue({
el: '#app',
render: h => h(App),
store,
beforeCreate() {
Vue.prototype.$bus = this
},
})
App.vue
<template>
<div>
<Count/>
<hr>
<Person/>
</div>
</template>
<script>
import Count from './components/Count'
import Person from './components/Person'
export default {
name:'App',
components:{Count,Person},
}
</script>
count.js
//求和相关的配置
export default {
namespaced:true,
actions:{
//准备actions——用于响应组件中的动作
addOdd(context,value){
if(context.state.sum % 2){
context.commit('ADD',value)
}
},
addWait(context,value){
setTimeout(() => {
context.commit('ADD',value)
}, 500);
}
},
mutations:{
ADD(state,value){
console.log('mutations中的ADD被调用了')
state.sum += value
},
JIAN(state,value){
console.log('mutations中的JIAN被调用了')
state.sum -= value
},
},
state:{
sum:0, //当前的和
school:'成都大学',
subject:'前端',
},
getters:{
bigSum(state){
return state.sum * 10
}
}
}
person.js
//人员管理相关的配置
import axios from 'axios'
import {nanoid} from 'nanoid'
export default {
namespaced:true,
actions:{
addPersonWang(context,value){
if(value.name.indexOf('王') === 0){
context.commit('ADD_PERSON',value)
}else{
alert('添加的人必须姓王!')
}
},
addPersonServer(context){
axios.get('https://api.uixsj.cn/hitokoto/get?type=social').then(
response => {
context.commit('ADD_PERSON',{id:nanoid(),name:response.data})
},
error => {
alert(error.message)
}
)
}
},
mutations:{
ADD_PERSON(state,value){
console.log('mutations中的ADD_PERSON被调用了')
state.personList.unshift(value)
}
},
state:{
personList:[
{id:'001',name:'张三'}
]
},
getters:{
firstPersonName(state){
return state.personList[0].name
}
}
}
index.js
//该文件用于创建Vuex中最为核心的store
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
import countOptions from './count'
import personOptions from './person'
//应用Vuex插件
Vue.use(Vuex)
//创建并暴露store
export default new Vuex.Store({
modules:{
countAbout:countOptions,
personAbout:personOptions
}
})
Count.vue
<template>
<div>
<h1>当前求和为:{{sum}}</h1>
<h2>当前求和放大10倍为:{{bigSum}}</h2>
<h2>我在{{school}},学习{{subject}}</h2>
<h3 style="color: red;">Person组件的总人数是:{{personList.length}}</h3>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="increament(n)">+</button>
<button @click="decreament(n)">-</button>
<button @click="increamentOdd(n)">当前求和为奇数再加</button>
<button @click="increamentWait(n)">等一等再加</button>
</div>
</template>
<script>
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
export default {
name:'Count',
data() {
return {
n:1,//用户选择的 数字
}
},
computed:{
// 借助mapState生成计算属性,从state中读取数据。(数组写法)
...mapState('countAbout',['sum','school','subject','personList']),
...mapState('personAbout',['personList']),
//借助mapGetters生成计算属性,从getters中读取数据。(对象写法)
...mapGetters('countAbout',{bigSum:'bigSum'})
},
methods: {
//借助mapMutations生成对应的方法,方法中会调用commit去联系mutations(对象写法)
...mapMutations('countAbout',{increament:'ADD',decreament:'JIAN'}),
//借助mapActions生成对应的方法,方法中会调用dispatch去联系action(对象写法)
...mapActions('countAbout',{increamentOdd:'addOdd',increamentWait:'addWait'}),
},
}
</script>
<style>
button{
margin-left: 5px;
}
</style>
Person.vue
<template>
<div>
<h1>人员列表</h1>
<h3 style="color: red;">Count组件求和为:{{sum}}</h3>
<h3>列表中第一个人的名字是:{{firstPersonName}}</h3>
<input type="text" placeholder="请输入名字" v-model="name">
<button @click="add">添加</button>
<button @click="addWang">添加一个姓王的人</button>
<button @click="addPersonServer">添加一个人,名字随机</button>
<ul>
<li v-for="(p, index) in personList" :key="index">{{p.name}}</li>
</ul>
</div>
</template>
<script>
import {nanoid} from 'nanoid'
export default {
name:'Person',
data() {
return {
name:'',
}
},
computed:{
personList(){
return this.$store.state.personAbout.personList
},
sum(){
return this.$store.state.countAbout.sum
},
firstPersonName(){
return this.$store.getters['personAbout/firstPersonName']
}
},
methods: {
add(){
const personObj = {id:nanoid(),name:this.name}
this.$store.commit('personAbout/ADD_PERSON',personObj)
this.name = ''
},
addWang(){
const personObj = {id:nanoid(),name:this.name}
this.$store.dispatch('personAbout/addPersonWang',personObj)
this.name = ''
},
addPersonServer(){
this.$store.dispatch('personAbout/addPersonServer')
}
},
}
</script>
<style>
</style>
运行效果
总结
6 路由
6.1 简介
6.2 基本使用
安装:npm i vue-router@3
public中使用bootstarp.css的版本是3,所以vscode中需要安装bootstarp3的插件
index.html
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<!-- 针对IE浏览器的一个特殊配置,含义是让IE浏览器以最高的渲染级别渲染页面 -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- 开启移动端的理想视口 -->
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<!-- 配置页签图标 -->
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<!-- 引入第三方样式 -->
<link rel="stylesheet" href="<%= BASE_URL %>css/bootstrap.css">
<!-- 配置网页标题 -->
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<!-- 当浏览器不支持js时noscript中的元素就会被渲染 -->
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<!-- 容器 -->
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
main.js
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入VueRouter
import VueRouter from 'vue-router'
//引入路由器
import router from './router'
//关闭Vue的生产提示
Vue.config.productionTip = false
//应用插件
Vue.use(VueRouter)
//创建vm
new Vue({
el: '#app',
render: h => h(App),
router:router,
})
router/index.js
//该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router"
//引入组件
import About from '../components/About'
import Home from '../components/Home'
//创建并暴露一个路由器
export default new VueRouter({
routes:[
{
path:'/about',
component:About
},
{
path:'/home',
component:Home
}
]
})
App.vue
<template>
<div>
<div class="row">
<div class="col-xs-offset-2 col-xs-8">
<div class="page-header">
<h2>Vue Router Demo</h2>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-2 col-xs-offset-2">
<div class="list-group">
<!-- 原始html中我们使用a标签实现页面的跳转 -->
<!-- <a class="list-group-item" href="./about.html">About</a> -->
<!-- <a class="list-group-item active" href="./home.html">Home</a> -->
<!-- Vue中借助router-link标签实现路由的切换 -->
<router-link class="list-group-item" active-class="active" to="./about">About</router-link>
<router-link class="list-group-item" active-class="active" to="./home">Home</router-link>
</div>
</div>
<div class="col-xs-6">
<div class="panel">
<div class="panel-body">
<!-- 指定组件的呈现位置 -->
<router-view></router-view>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name:'App',
}
</script>
About.vue
<template lang="">
<div>
<h2>我是About的内容</h2>
</div>
</template>
<script>
export default {
name:'About'
}
</script>
Home.vue
<template lang="">
<div>
<h2>我是Home的内容</h2>
</div>
</template>
<script>
export default {
name:'Home'
}
</script>
运行效果
总结
6.3 注意点
6.4 多级路由
index.js
//该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router"
//引入组件
import About from '../pages/About'
import Home from '../pages/Home'
import News from '../pages/News'
import Message from '../pages/Message'
//创建并暴露一个路由器
export default new VueRouter({
routes:[
{
path:'/about',
component:About
},
{
path:'/home',
component:Home,
children:[
{
path:'news',
component:News
},
{
path:'message',
component:Message
}
]
}
]
})
Home.vue
<template lang="">
<div>
<h2>Home组件内容</h2>
<div>
<ul class="nav nav-tabs">
<li>
<router-link class="list-group-item" active-class="active" to="/home/news">News</router-link>
</li>
<li>
<router-link class="list-group-item" active-class="active" to="/home/message">Nessage</router-link>
</li>
</ul>
<router-view></router-view>
</div>
</div>
</template>
<script>
export default {
name:'Home'
}
</script>
运行效果
总结
6.5 路由的query参数
router/index.js
//该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router"
//引入组件
import About from '../pages/About'
import Home from '../pages/Home'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'
//创建并暴露一个路由器
export default new VueRouter({
routes:[
{
path:'/about',
component:About
},
{
path:'/home',
component:Home,
children:[
{
path:'news',
component:News
},
{
path:'message',
component:Message,
children:[
{
path:'detail',
component:Detail,
}
]
}
]
}
]
})
App.vue
<template>
<div>
<div class="row">
<Banner/>
</div>
<div class="row">
<div class="col-xs-2 col-xs-offset-2">
<div class="list-group">
<!-- 原始html中我们使用a标签实现页面的跳转 -->
<!-- <a class="list-group-item" href="./about.html">About</a> -->
<!-- <a class="list-group-item active" href="./home.html">Home</a> -->
<!-- Vue中借助router-link标签实现路由的切换 -->
<router-link class="list-group-item" active-class="active" to="./about">About</router-link>
<router-link class="list-group-item" active-class="active" to="./home">Home</router-link>
</div>
</div>
<div class="col-xs-6">
<div class="panel">
<div class="panel-body">
<!-- 指定组件的呈现位置 -->
<router-view></router-view>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import Banner from './components/Banner'
export default {
name:'App',
components:{Banner}
}
</script>
Home.vue
<template lang="">
<div>
<h2>Home组件内容</h2>
<div>
<ul class="nav nav-tabs">
<li>
<router-link class="list-group-item" active-class="active" to="/home/news">News</router-link>
</li>
<li>
<router-link class="list-group-item" active-class="active" to="/home/message">Nessage</router-link>
</li>
</ul>
<router-view></router-view>
</div>
</div>
</template>
<script>
export default {
name:'Home'
}
</script>
Message.vue
<template>
<div>
<ul>
<li v-for="(item, index) in messageList" :key="item.id">
<!-- 跳转路由并携带query参数,to的字符串写法 -->
<!-- <router-link :to="`/home/message/detail?id=${item.id}&title=${item.title}`">{{item.title}}</router-link> -->
<!-- 跳转路由并携带query参数,to的对象写法 -->
<router-link :to="{
path:'/home/message/detail',
query:{
id:item.id,
title:item.title
}
}">
{{item.title}}
</router-link>
</li>
</ul>
<hr>
<router-view></router-view>
</div>
</template>
<script>
export default {
name:'Message',
data() {
return {
messageList:[
{id:'001',title:'消息001'},
{id:'002',title:'消息002'},
{id:'003',title:'消息003'}
]
}
},
}
</script>
Detail.vue
<template lang="">
<div>
<ul>
<li>消息编号:{{$route.query.id}}</li>
<li>消息标题:{{$route.query.title}}</li>
</ul>
</div>
</template>
<script>
export default {
name:'Detail',
}
</script>
运行效果
总结
6.6 命名路由
6.7 路由的params参数
router/index.js
//该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router"
//引入组件
import About from '../pages/About'
import Home from '../pages/Home'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'
//创建并暴露一个路由器
export default new VueRouter({
routes:[
{
name:'guanyu',
path:'/about',
component:About
},
{
path:'/home',
component:Home,
children:[
{
path:'news',
component:News
},
{
path:'message',
component:Message,
children:[
{
name:'xiangqing',
path:'detail/:id/:title',
component:Detail,
}
]
}
]
}
]
})
Message.vue
<template>
<div>
<ul>
<li v-for="(item, index) in messageList" :key="item.id">
<!-- 跳转路由并携带params参数,to的字符串写法 -->
<!-- <router-link :to="`/home/message/detail/${item.id}/${item.title}`">{{item.title}}</router-link> -->
<!-- 跳转路由并携带query参数,to的对象写法 -->
<router-link :to="{
name:'xiangqing',
params:{
id:item.id,
title:item.title
}
}">
{{item.title}}
</router-link>
</li>
</ul>
<hr>
<router-view></router-view>
</div>
</template>
<script>
export default {
name:'Message',
data() {
return {
messageList:[
{id:'001',title:'消息001'},
{id:'002',title:'消息002'},
{id:'003',title:'消息003'}
]
}
},
}
</script>
Detail.vue
<template lang="">
<div>
<ul>
<li>消息编号:{{$route.params.id}}</li>
<li>消息标题:{{$route.params.title}}</li>
</ul>
</div>
</template>
<script>
export default {
name:'Detail',
}
</script>
总结
6.8 路由的props配置
router/index.js
//该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router"
//引入组件
import About from '../pages/About'
import Home from '../pages/Home'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'
//创建并暴露一个路由器
export default new VueRouter({
routes:[
{
name:'guanyu',
path:'/about',
component:About
},
{
path:'/home',
component:Home,
children:[
{
path:'news',
component:News
},
{
path:'message',
component:Message,
children:[
{
name:'xiangqing',
path:'detail/:id/:title',
component:Detail,
//props的第一种写法,值为对象,该对象中的所有key-value都会以props的形式传给Detail组件。
// props:{a:1,b:'hello'}
//props的第二种写法,值为布尔值,若布尔值为真,就会把该路由组件收到的所有params参数,以props的形式传给Detail组件。
// props:true,
//props的第三种写法,值为函数
props($route){
return {id:$route.query.id,title:$route.query.title}
}
}
]
}
]
}
]
})
Message.vue
<template>
<div>
<ul>
<li v-for="(item, index) in messageList" :key="item.id">
<!-- 跳转路由并携带params参数,to的字符串写法 -->
<!-- <router-link :to="`/home/message/detail/${item.id}/${item.title}`">{{item.title}}</router-link> -->
<!-- 跳转路由并携带query参数,to的对象写法 -->
<router-link :to="{
name:'xiangqing',
query:{
id:item.id,
title:item.title
}
}">
{{item.title}}
</router-link>
</li>
</ul>
<hr>
<router-view></router-view>
</div>
</template>
<script>
export default {
name:'Message',
data() {
return {
messageList:[
{id:'001',title:'消息001'},
{id:'002',title:'消息002'},
{id:'003',title:'消息003'}
]
}
},
}
</script>
Detail.vue
<template lang="">
<div>
<ul>
<li>消息编号:{{id}}</li>
<li>消息标题:{{title}}</li>
</ul>
</div>
</template>
<script>
export default {
name:'Detail',
props:['id','title']
}
</script>
总结
6.9 router-link的replace属性
6.10 编程式路由导航
Message.vue
<template>
<div>
<ul>
<li v-for="(item, index) in messageList" :key="item.id">
<!-- 跳转路由并携带params参数,to的字符串写法 -->
<!-- <router-link :to="`/home/message/detail/${item.id}/${item.title}`">{{item.title}}</router-link> -->
<!-- 跳转路由并携带query参数,to的对象写法 -->
<router-link :to="{
name:'xiangqing',
query:{
id:item.id,
title:item.title
}
}">
{{item.title}}
</router-link>
<button @click="pushShow(item)">push查看</button>
<button @click="replaceShow(item)">replace查看</button>
</li>
</ul>
<hr>
<router-view></router-view>
</div>
</template>
<script>
export default {
name:'Message',
data() {
return {
messageList:[
{id:'001',title:'消息001'},
{id:'002',title:'消息002'},
{id:'003',title:'消息003'}
]
}
},
methods: {
pushShow(item){
this.$router.push({
name:'xiangqing',
query:{
id:item.id,
title:item.title
}
})
},
replaceShow(item){
this.$router.replace({
name:'xiangqing',
query:{
id:item.id,
title:item.title
}
})
}
},
}
</script>
Banner.vue
<template>
<div>
<div class="col-xs-offset-2 col-xs-8">
<div class="page-header">
<h2>Vue Router Demo</h2>
<button @click="back">后退</button>
<button @click="forward">前进</button>
<button @click="test">测试一下go</button>
</div>
</div>
</div>
</template>
<script>
export default {
name:'Banner',
methods: {
back(){
this.$router.back()
},
forward(){
this.$router.forward()
},
test(){
this.$router.go(-2)//正数表示前进几步,负数表示后退几步
}
},
}
</script>
总结
6.11 缓存路由组件
Home.vue
<template lang="">
<div>
<h2>Home组件内容</h2>
<div>
<ul class="nav nav-tabs">
<li>
<router-link class="list-group-item" active-class="active" to="/home/news">News</router-link>
</li>
<li>
<router-link class="list-group-item" active-class="active" to="/home/message">Nessage</router-link>
</li>
</ul>
<keep-alive include="News"> <!-- 组件名 -->
<router-view></router-view>
</keep-alive>
</div>
</div>
</template>
<script>
export default {
name:'Home'
}
</script>
News.vue
<template>
<div>
<li>news001 <input type="text"></li>
<li>news002 <input type="text"></li>
<li>news003 <input type="text"></li>
</div>
</template>
<script>
export default {
name:'News'
}
</script>
<style>
</style>
运行效果
缓存多个组件
总结
6.12 新的生命周期钩子
News.vue
<template>
<div>
<li :style="{opacity}">欢迎学习vue</li>
<li>news001 <input type="text"></li>
<li>news002 <input type="text"></li>
<li>news003 <input type="text"></li>
</div>
</template>
<script>
export default {
name:'News',
data() {
return {
opacity:1
}
},
/* beforeDestroy() {
clearInterval(this.timer)
},
mounted() {
this.timer = setInterval(() => {
this.opacity -= 0.01
if(this.opacity <= 0){
this.opacity = 1
}
}, 16);
}, */
activated() {
console.log('News组件被激活了')
this.timer = setInterval(() => {
this.opacity -= 0.01
if(this.opacity <= 0){
this.opacity = 1
}
}, 16);
},
deactivated() {
console.log('News组件失活了')
clearInterval(this.timer)
},
}
</script>
<style>
</style>
运行效果
总结
6.13 全局路由守卫
router/index.js
//该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router"
//引入组件
import About from '../pages/About'
import Home from '../pages/Home'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'
//创建并暴露一个路由器
const router = new VueRouter({
routes:[
{
name:'guanyu',
path:'/about',
component:About,
meta:{title:'关于'}
},
{
name:'zhuye',
path:'/home',
component:Home,
meta:{title:'主页'},
children:[
{
name:'xinwen',
path:'news',
component:News,
meta:{isAuth:true,title:'新闻'}
},
{
name:'xiaoxi',
path:'message',
component:Message,
meta:{isAuth:true,title:'消息'},
children:[
{
name:'xiangqing',
path:'detail/:id/:title',
component:Detail,
meta:{isAuth:true,title:'详情'},
//props的第一种写法,值为对象,该对象中的所有key-value都会以props的形式传给Detail组件。
// props:{a:1,b:'hello'}
//props的第二种写法,值为布尔值,若布尔值为真,就会把该路由组件收到的所有params参数,以props的形式传给Detail组件。
// props:true,
//props的第三种写法,值为函数
props($route){
return {id:$route.query.id,title:$route.query.title}
}
}
]
}
]
}
]
})
//全局前置路由守卫---初始化的时候被调用、每次路由切换之前被调用
router.beforeEach((to,from,next) => {
console.log('前置路由守卫',to,from,next)
if(to.meta.isAuth){ //判断是否需要鉴权
if(localStorage.getItem('school') === 'chengdu1'){
next()
}else{
alert('学校名不对,无权限查看!')
}
}else{
next()
}
})
//全局后置路由守卫---初始化的时候被调用、每次路由切换之后被调用
router.afterEach((to,from)=>{
console.log('后置路由守卫',to,from)
document.title = to.meta.title || '信息系统'
})
export default router
运行效果
总结
6.14 独享路由守卫
router/index.js
//该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router"
//引入组件
import About from '../pages/About'
import Home from '../pages/Home'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'
//创建并暴露一个路由器
const router = new VueRouter({
routes:[
{
name:'guanyu',
path:'/about',
component:About,
meta:{title:'关于'}
},
{
name:'zhuye',
path:'/home',
component:Home,
meta:{title:'主页'},
children:[
{
name:'xinwen',
path:'news',
component:News,
meta:{isAuth:true,title:'新闻'},
beforeEnter: (to, from, next) => {
router.beforeEach((to,from,next) => {
console.log('独享路由守卫',to,from,next)
if(to.meta.isAuth){ //判断是否需要鉴权
if(localStorage.getItem('school') === 'chengdu1'){
next()
}else{
alert('学校名不对,无权限查看!')
}
}else{
next()
}
})
}
},
{
name:'xiaoxi',
path:'message',
component:Message,
meta:{isAuth:true,title:'消息'},
children:[
{
name:'xiangqing',
path:'detail/:id/:title',
component:Detail,
meta:{isAuth:true,title:'详情'},
//props的第一种写法,值为对象,该对象中的所有key-value都会以props的形式传给Detail组件。
// props:{a:1,b:'hello'}
//props的第二种写法,值为布尔值,若布尔值为真,就会把该路由组件收到的所有params参数,以props的形式传给Detail组件。
// props:true,
//props的第三种写法,值为函数
props($route){
return {id:$route.query.id,title:$route.query.title}
}
}
]
}
]
}
]
})
//全局前置路由守卫---初始化的时候被调用、每次路由切换之前被调用
/* router.beforeEach((to,from,next) => {
console.log('前置路由守卫',to,from,next)
if(to.meta.isAuth){ //判断是否需要鉴权
if(localStorage.getItem('school') === 'chengdu1'){
next()
}else{
alert('学校名不对,无权限查看!')
}
}else{
next()
}
}) */
//全局后置路由守卫---初始化的时候被调用、每次路由切换之后被调用
router.afterEach((to,from)=>{
console.log('后置路由守卫',to,from)
document.title = to.meta.title || '信息系统'
})
export default router
运行效果
总结
6.15 组件内守卫
About.vue
<template lang="">
<div>
<h2>我是About的内容</h2>
</div>
</template>
<script>
export default {
name:'About',
//通过路由规则,进入该组件时被调用
beforeRouteEnter (to, from, next) {
console.log('About--beforeRouteEnter',to,from)
if(to.meta.isAuth){ //判断是否需要鉴权
if(localStorage.getItem('school') === 'chengdu1'){
next()
}else{
alert('学校名不对,无权限查看!')
}
}else{
next()
}
},
//通过路由规则,离开该组件时被调用
beforeRouteLeave (to, from, next) {
console.log('About--beforeRouteLeave',to,from)
next()
}
}
</script>
总结
6.16 路由器两种工作模式
router/index.js
//该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router"
//引入组件
import About from '../pages/About'
import Home from '../pages/Home'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'
//创建并暴露一个路由器
const router = new VueRouter({
// mode:'history',
mode:'hash',
routes:[
{
name:'guanyu',
path:'/about',
component:About,
meta:{isAuth:true,title:'关于'}
},
{
name:'zhuye',
path:'/home',
component:Home,
meta:{title:'主页'},
children:[
{
name:'xinwen',
path:'news',
component:News,
meta:{isAuth:true,title:'新闻'},
/* beforeEnter: (to, from, next) => {
router.beforeEach((to,from,next) => {
console.log('独享路由守卫',to,from,next)
if(to.meta.isAuth){ //判断是否需要鉴权
if(localStorage.getItem('school') === 'chengdu1'){
next()
}else{
alert('学校名不对,无权限查看!')
}
}else{
next()
}
})
} */
},
{
name:'xiaoxi',
path:'message',
component:Message,
meta:{isAuth:true,title:'消息'},
children:[
{
name:'xiangqing',
path:'detail/:id/:title',
component:Detail,
meta:{isAuth:true,title:'详情'},
//props的第一种写法,值为对象,该对象中的所有key-value都会以props的形式传给Detail组件。
// props:{a:1,b:'hello'}
//props的第二种写法,值为布尔值,若布尔值为真,就会把该路由组件收到的所有params参数,以props的形式传给Detail组件。
// props:true,
//props的第三种写法,值为函数
props($route){
return {id:$route.query.id,title:$route.query.title}
}
}
]
}
]
}
]
})
//全局前置路由守卫---初始化的时候被调用、每次路由切换之前被调用
/* router.beforeEach((to,from,next) => {
console.log('前置路由守卫',to,from,next)
if(to.meta.isAuth){ //判断是否需要鉴权
if(localStorage.getItem('school') === 'chengdu1'){
next()
}else{
alert('学校名不对,无权限查看!')
}
}else{
next()
}
}) */
//全局后置路由守卫---初始化的时候被调用、每次路由切换之后被调用
router.afterEach((to,from)=>{
console.log('后置路由守卫',to,from)
document.title = to.meta.title || '信息系统'
})
export default router
总结
7 Vue UI组件库
7.1 element-ui
安装 npm i element-ui
main.js
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入ElementUI组件库
import ElementUI from 'element-ui';
//引入ElementUI全部样式
import 'element-ui/lib/theme-chalk/index.css';
//关闭Vue的生产提示
Vue.config.productionTip = false
//应用ElementUI
Vue.use(ElementUI);
//创建vm
new Vue({
el: '#app',
render: h => h(App),
})
App.vue
<template>
<div>
<button>原生的按钮</button>
<input type="text">
<el-row>
<el-button>默认按钮</el-button>
<el-button type="primary">主要按钮</el-button>
<el-button type="success">成功按钮</el-button>
<el-button type="info">信息按钮</el-button>
<el-button type="warning">警告按钮</el-button>
<el-button type="danger">危险按钮</el-button>
</el-row>
</div>
</template>
<script>
export default {
name:'App'
}
</script>
运行效果
7.2 按需引入
**安装 ** npm install babel-plugin-component -D
babel.config.js
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset',
["@babel/env", { "modules": false }]
],
plugins: [
[
"component",
{
"libraryName": "element-ui",
"styleLibraryName": "theme-chalk"
}
]
]
}
main.js
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//完整引入
//引入ElementUI组件库
// import ElementUI from 'element-ui';
//引入ElementUI全部样式
// import 'element-ui/lib/theme-chalk/index.css';
//按需引入
import { Button, Row } from 'element-ui'
//关闭Vue的生产提示
Vue.config.productionTip = false
//应用ElementUI
// Vue.use(ElementUI);
Vue.component(Button.name, Button);
//创建vm
new Vue({
el: '#app',
render: h => h(App),
})
App.vue
<template>
<div>
<button>原生的按钮</button>
<input type="text">
<el-row>
<el-button>默认按钮</el-button>
<el-button type="primary">主要按钮</el-button>
<el-button type="success">成功按钮</el-button>
<el-button type="info">信息按钮</el-button>
<el-button type="warning">警告按钮</el-button>
<el-button type="danger">危险按钮</el-button>
</el-row>
</div>
</template>
<script>
export default {
name:'App'
}
</script>
运行效果