参考

Vue入门

Vue (读音 /vjuː/,类似于 view) 是一套用于构建用户界面的渐进式框架。与其它大型框架不同的是,Vue 被设计为可以自底向上逐层应用。Vue 的核心库只关注视图层,不仅易于上手,还便于与第三方库或既有项目整合。另一方面,当与现代化的工具链以及各种支持类库结合使用时,Vue 也完全能够为复杂的单页应用提供驱动。

搭建Vue开发环境

  1. 官方文档中下载开发版本生产版本;

  2. 在html中引入Vue

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    <script type="text/javascript" src="本地vue.js的路径"></script>

    <!-- 例如 -->
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>搭建Vue开发环境</title>
    <script type="text/javascript" src="../js/vue.js"></script>
    </head>
    <body>

    </body>
    </html>
  3. 处理控制台出现的警告
  • 安装开发者工具
    Vue.js devtools是基于chrome的一款浏览器插件,是开发过程中必不可少的,其高效、简洁、方便的特点深受vue开发者的喜爱。
    前往下载

  • 下载完成后点击谷歌浏览器右上角的扩展程序->管理扩展程序->打开开发者模式,将下载好的文件拖入页面。

  • 最后再点击谷歌浏览器右上角的扩展程序,可以看到Vue.js devtools,点击右边的小图钉将它固定在页面导航栏里面,以后方便使用。

  • 阻止 vue 在启动时生成生产提示:

    1
    2
    3
    <script type="text/javascript">
    Vue.config.productionTip = false;//设置为 false 以阻止 vue 在启动时生成生产提示。
    </script>

    将vue.js中第367行productionTip: true改成productionTip: false

模板语法

Vue模板语法有2大类:

  1. 插值语法
    功能: 用于解析标签体内容。
    写法: {{xxx}},xxx是js表达式,且可以直接读取到data中的所有属性
  2. 指令语法
    功能: 用于解析标签(包括: 标签属性、标签体内容、绑定事件…..)。
    举例: v-bind:href="xxx"或简写为 :href="xxx",xxx同样要写js表达式且可以直接读取到data中的所有属性。
    备注: Vue中有很多的指令,且形式都是: v-????,此处我们只是拿v-bind举个例子。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!-- 准备一个容器 -->
<div class="box1">
<h1>插值标签</h1>
<h3>hello,{{name}}</h3>
<hr/>
<h1>指令语法</h1>
<a :href="url" target="_blank">点我去博客</a>
<!-- <a v-bind:href="url" target="_blank">点我去博客</a> -->
</div>

<script type="text/javascript">
new Vue({
el: '.box1', //el用于指定当前vue实例为哪个容器服务
data: { //data中用于存储数据
name: 'hhh',
url: 'http://githubxxx17.github.io'
}
})
</script>

数据绑定

Vue中有2种数据绑定的方式:

  1. 单向绑定(v-bind): 数据只能从data流向页面。
  2. 双向绑定(v-model): 数据不仅能从data流向页面,还可以从页面流向data。
    备注:
    双向绑定一般都应用在表单类元素上 (如: input、select等)
    v-model:value 可以简写为 v-model,因为v-model默认收集的就是value值。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!-- 普通写法 -->
<!-- <div class="box2">
单向数据绑定:<input type="text" v-bind:value="name"><br/>
双向数据绑定:<input type="text" v-model:value="name"><br/>
</div> -->

<!-- 简写 -->
<div class="box2">
单向数据绑定:<input type="text" :value="name"><br/>
双向数据绑定:<input type="text" v-model="name"><br/>
<!-- v-model只能用在表单类元素(输入类元素)上 -->
</div>

<script type="text/javascript">
new Vue({
el: '.box2',
data: {
name: 'xxx'
}
})
</script>

el和data的两种写法

data与el的2种写法

  1. e1有2种写法:
    (1).new Vue时候配置el属性。
    (2).先创建Vue实例,随后再通过vm.$mount('#root')指定el的值
  2. data有2种写法:
    (1).对象式
    (2).函数式
    如何选择: 目前哪种写法都可以,以后学习到组件时,data必须使用函数式,否则会报错。
  3. 一个重要的原则:
    由Vue管理的函数,一定不要写箭头函数,一旦写了箭头函数,this就不再是Vue实例了。
1
2
3
<div id="root">
<h1>hello,{{name}}</h1>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//el的两种写法
const x = new Vue({
// el: '#root', //第一种写法
data: {
name: 'world'
},
});
x.$mount('#root');//第二种写法 mount:挂载


//data的两种写法
new Vue({
el: '#root',
//data的第一种写法:对象式
data: {
name: 'world'
}

//data的第二种写法:函数式
data(){
// 函数this为Vue实例对象
return {
name: 'world'
}
}
})

数据代理

回顾Object.defineProperty方法

Object.defineProperty(对象,属性,{value:值});

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
let num = 18
let person = {
name: 'h'
}

Object.defineProperty(person,'age',{
// value: 18,
enumerable:true,//控制属性是否可以枚举,默认值为false
writable:true, //控制属性是否可以修改,默认值为false
configurable: true,//控制属性是否可以被删除,默认值为false

//当有人读取person的age属性时,get函数(getter)就会被调用,且返回值就是age的值
get(){
return num;
},

//当有人修改person的age属性时,set函数(setter)就会被调用,且会收到修改的具体值
set(value){
num = value;
}
})

数据代理概念:通过一个对象代理对另一个对象中属性的操作(读/写)

  1. Vue中的数据代理:
    通过vm对象来代理data对象中属性的操作(读/写)
  2. vue中数据代理的好处:
    更加方便的操作data中的数据
  3. 基本原理:
    通过object.defineProperty()把data对象中所有属性添加到vm上。
    为每一个添加到vm上的属性,都指定一个getter/setter。
    在getter/setter内部去操作 (读/写)data中对应的属性。
1
2
3
4
5
6
7
8
9
10
11
12

let obj = { x: 100 };
let obj2 = { y: 200 };
Object.defineproperty(obj2, 'x', {
get() {
return obj.x;
},

set(value) {
obj.x = value;
}
})

事件处理

事件的基本使用:

  1. 使用v-on:xxx@xxx 绑定事件,其中xxx是事件名;
  2. 事件的回调需要配置在methods对象中,最终会在vm上;
  3. methods中配置的函数,不要用箭头函数! 否则this就不是vm了;
  4. methods中配置的函数,都是被Vue所管理的函数,this的指向是vm 或 组件实例对象;
  5. @click="demo"@click="demo($event)" 效果一致,但后者可以传参。
1
2
3
4
5
6
<div id="root">
<h2>学习数据处理</h2>
<!-- <button v-on:click = "showinfo">点我显示提示信息</button> -->
<button @click = "showinfo1">点我显示提示信息(不传参)</button>
<button @click = "showinfo2($event,6)">点我显示提示信息(传参)</button>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
new Vue({
el: '#root',
data:{
name: 'xxx',
},
methods:{
showinfo1(){
alert('你好');
},
showinfo2(event,num){
alert('你好'+num);
console.log(event.target.innerText);
}
}
})

Vue中的事件修饰符:

  1. prevent:阻止默认事件 (常用);
  2. stop:阻止事件冒泡(常用);
  3. once:事件只触发一次(常用);
  4. capture:使用事件的捕获模式;
  5. self:只有event.target是当前操作的元素是才触发事件;
  6. passive:事件的默认行为立即执行,无需等待事件回调执行完毕。

注意:修饰符可以连续写,例如@click.stop.prevent

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<div id="root">
<!-- 阻止默认事件 (常用) -->
<a href="http://githubxxx17.github.io" @click.prevent="goto">点我去博客</a>
<!-- 阻止事件冒泡(常用) -->
<div class="btn1" @click="showinfo1">
<button @click.stop="showinfo1">点我显示提示信息</button>
</div>
<!-- 事件只触发一次(常用) -->
<button @click.once="showinfo1">点我显示提示信息</button>
<!-- 使用事件的捕获模式 -->
<div class="box1" @click.capture = "showMsg(1)">
div1
<div class="box2" @click = "showMsg(2)">
div2
</div>
</div>
<!-- 只有event.target是当前操作的元素是才触发事件 -->
<div class="btn1" @click.self="showinfo1">
<button @click="showinfo1">点我显示提示信息</button>
</div>
<!-- 事件的默认行为立即执行,无需等待事件回调执行完毕 -->
<ul @wheel="wheel">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
* {
margin: 0;
padding: 0;
}
.btn1 {
margin: 10px;
width: 200px;
height: 50px;
background-color: aquamarine;
display: flex;
align-items: center;
justify-content: center;
}
.box1 {
margin: 10px;
width: 100px;
height: 100px;
padding: 5px;
background-color: beige;
}

.box2 {
width: 50px;
height: 50px;
padding: 5px;
background-color: rgb(103, 230, 255);
}

ul {
height: 300px;
width: 500px;
background-color: antiquewhite;
overflow: auto;
}

li {
width: 100%;
height: 200px;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
new Vue({
el: '#root',
data:{
name: 'xxx',
},
methods:{
showinfo1(){
alert('你好');
},
showinfo2(event,num){
alert('你好'+num);
console.log(event.target.innerText);
},
goto(){
alert('去博客');
},
showMsg(a){
alert(a);
},
wheel(){
for(let i = 0;i < 10000;i++){
console.log(1);
}
console.log(2);
}
}
})
  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.自定义键名 = 键码,可以去定制按键别名。
1
2
3
4
5
6
7
8
9
10
11
<div id="root">
<input type="text" @keyup.enter="keyup">
<!-- Vue未提供别名的按键,可以使用按键原始的key值去绑定,但注意要转为kebab-case -->
<input type="text" @keyup.caps-lock="keyup">
<!-- 按下ctrl的同时,再按下其他键,随后释放其他键,事件才被触发 -->
<input type="text" @keyup.ctrl.y="keyup">
<!-- 使用keycode去指定具体的按键(不推荐) -->
<input type="text" @keyup.13="keyup">
<!-- 自定义键名 -->
<input type="text" @keyup.huiche="keyup">
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 自定义键名
Vue.config.keyCodes.huiche = 13

new Vue({
el: '#root',
data:{
name: 'xxx',
},
methods:{
keyup(e){
console.log(e.target.value);
}
}
})

计算属性

姓名案例(methods实现)
1
2
3
4
5
<div id="root">
姓:<input type="text" v-model="firstName"><br>
名:<input type="text" v-model="lastName"><br>
姓名:<span>{{fullName()}}</span>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
new Vue({
el:'#root',
data:{
firstName:'张',
lastName:'三'
},
methods:{
fullName(){
return this.firstName + '-' + this.lastName;
}
}
})

计算属性

  1. 定义:要用的属性不存在,要通过已有属性计算得来。
  2. 原理:底层借助了objcet.defineproperty方法提供的getter和setter。
  3. get函数什么时候执行?
    (1).初次读取时会执行一次。
    (2).当依赖的数据发生改变时会被再次调用。
  4. 优势:与methods实现相比,内部有缓存机制(复用) ,效率更高,调试方便。
  5. 备注
    (1).计算属性最终会出现在vm上,直接读取使用即可。
    (2).如果计算属性要被修改,那必须写set函数去响应修改,且set中要引起计算时依赖的数据发生改变。
1
2
3
4
5
<div id="root">
姓:<input type="text" v-model="firstName"><br>
名:<input type="text" v-model="lastName"><br>
姓名:<span>{{fullName}}</span>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
new Vue({
el:'#root',
data:{
firstName:'张',
lastName:'三'
},
computed:{
fullName:{
//get有什么作用?
//当有人读取fulIName时,get就会被调用,且返回值就作为fulIName的值
//get什么时候调用?
//1.初次读取fulName时。2.所依赖的数据发生变化时。
get(){
return this.firstName + '-' + this.lastName;
},
//get什么时候调用?
//当fulIName被修改时。
set(){
console.log('set',value);
const arr = value.split('-');
this.firstName = arr[o];
this.lastName = arr[1];
}
},
//简写,只调用get时
// fullName(){
// return this.firstName + '-' + this.lastName;
// }
}
})

监视属性

监视属性watch:

  1. 当被监视的属性变化时,回调函数自动调用,进行相关操作
  2. 监视的属性必须存在,才能进行监视!!
  3. 监视的两种写法:
    (1). new Vue时传入watch配置
    (2). 通过vm.$watch监视
1
2
3
4
<div id="root">
<h1>今天天气很{{info}}</h1>
<button @click="changeWeather">切换</button>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
const vm = new Vue({
el:'#root',
data:{
ishot: true
},
computed:{
info(){
return this.ishot ? "炎热" : "凉爽";
}
},
methods: {
changeWeather(){
this.ishot = !this.ishot;
}
},
watch:{//watch第一种写法
ishot:{
immediate:true,//初始化时让handler调用一下,默认值为false
//handler什么时候调用? 当isHot发生改变时。
handler(newValue,oldValue){
console.log("isHot被修改了" ,newValue,oldValue);
}
}

//简写
// ishot(newValue,oldValue){
// console.log("isHot被修改了" ,newValue,oldValue);
// }
}
})

//watch第二种写法
vm.$watch('ishot',{
handler(newValue,oldValue){
console.log("isHot被修改了" ,newValue,oldValue);
}
})

深度监视:
(1).Vue中的watch默认不监测对象内部值的改变 (一层)。
(2).配置deep:true可以监测对象内部值改变(多层)。
备注:
(1).Vue自身可以监测对象内部值的改变,但Vue提供的watch默认不可以!
(2).使用watch时根据数据的具体结构,决定是否采用深度监视。

1
2
3
4
5
6
7
<div id="root">
<h3>a的值是:{{numbers.a}}</h3>
<button @click="numbers.a++">点我让a+1</button>
<h3>b的值是:{{numbers.b}}</h3>
<button @click="numbers.b++">点我b+1</button>
<button @click="numbers = {a:666,b:888}">彻底替换numbers</button>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const vm = new Vue({
el:'#root',
data:{
numbers: {
a: 1,
b: 1
}
},
watch:{
//监视多级结构中某个属性的变化
'numbers.a': {
handler(){
console.log("a被改变了");
}
},
//监视多级结构中所有属性的变化
numbers: {
deep:true,
handler(){
console.log('numbers改变了');
}
}
}
})

computed和watch之间的区别:

  1. computed能完成的功能,watch都可以完成。
  2. watch能完成的功能,computed不一定能完成,例如: watch可以进行异步操作。
    两个重要的小原则:
  3. 所被Vue管理的函数,最好写成普通函数,这样this的指向才是vm 或 组件实例对象。
  4. 所有不被Vue所管理的函数(定时器的回调函数、ajax的回调函数等) ,最好写成箭头函数,这样this的指向才是vm 或 组件实例对象。

绑定样式

  1. class样式
    写法:class="xxx",xxx可以是字符串、对象、数组。
    字符串写法适用于:类名不确定,要动态获取。
    对象写法适用于:要绑定多个样式,个数不确定,名字也不确定。
    数组写法适用于:要绑定多个样式,个数确定,名字也确定,但不确定用不用
  2. style样式
    :style="{fontsize: xxx}"其中xxx是动态值。
    :style="[a,b]"其中a、b是样式对象。
1
2
3
4
5
6
7
8
9
10
11
12
<div id="root">
<!-- 绑定class样式--字符串写法,适用于:样式的类名不确定,需要动态指定 -->
<div class="box" :class="color" @click="changeColor"><h3>点我变色</h3></div>
<!-- 绑定class样式--数组写法,适用于: 要绑定的样式个数不确定、名字也不确定 -->
<div class="box" :class="classArr"><h3>数组写法</h3></div>
<!-- 绑定class样式--对象写法,适用于: 要绑定的样式个数确定、名字也确定,但要动态决定用不用 -->
<div class="box" :class="classObj"><h3>对象写法</h3></div>
<!-- 绑定style样式--对象写法 -->
<div class="box" :style="styleObj"><h3>绑定style样式</h3></div>
<!-- 绑定style样式--对象写法 -->
<div class="box" :style="styleArr"><h3>绑定style样式</h3></div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
* {
padding: 0;
margin: 0;
}
.box {
margin-bottom: 20px;
width: 400px;
height: 200px;
text-align: center;
line-height: 200px;
font-size: 20px;
cursor: pointer;
user-select: none;
}
.blue {
background-color: aqua;
}
.green {
background-color: greenyellow;
}
.red {
background-color: red;
}
.yellow {
background-color: yellow;
}
.fontcolor {
color: rgb(239, 98, 255);
}
.border {
border: 1px solid #000;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
new Vue({
el: '#root',
data: {
color: 'blue',
classArr: ['yellow','fontcolor','border'],
classObj: {
yellow: true,
fontcolor : false,
border: true
},
styleObj: {
fontSize: '40px',
backgroundColor: 'aqua'
},
styleArr: [
{
fontSize: '30px',
backgroundColor: 'aqua'
},
{
border: '1px solid #000'
}
]
},
methods: {
changeColor(){
const color = ['blue','green','red','yellow'];
this.color = color[Math.floor(Math.random()*3)];
}
},
})

条件渲染

  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="表达式"
    适用于:切换频率较高的场景。
    特点:不展示的BOM元素未被移除,仅仅是使用样式隐藏掉。
  3. 备注:使用v-if的时,元素可能无法获取到,而使用v-show一定可以获取到。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<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="n1=== 3">Vue</div>
<div V-else>哈哈</div>

<!-- v-if与template的配合使用 -->
<template v-if="n === 1">
<h2>你好</h2>
<h2>尚硅谷</h2>
<h2>北京</h2>
</template>
</div>
1
2
3
4
5
6
7
new Vue({
el: '#root',
data:{
name: 'xxx17的博客',
n: 0
}
})

列表

列表渲染

v-for指令:

  1. 用于展示列表数据
  2. 语法: v-for="(item, index) in xxx" :key="yyy"
  3. 可遍历: 数组、对象、字符串 (用的很少)、指定次数(用的很少)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<div id="root">
<!-- 遍历数组 -->
<ul>
<li v-for="p in person" :key="p.id">{{p.id}}-{{p.name}}-{{p.age}}</li>
</ul>
<ul>
<li v-for="(p,index) in person" :key="index">{{index}}-{{p.name}}-{{p.age}}</li>
</ul>

<!-- 遍历对象 -->
<ul>
<li v-for="(value,k) in car" :key="k">{{k}}-{{value}}</li>
</ul>

<!-- 遍历字符串(用得少) -->
<ul>
<li v-for="(char,index) in str" :key="index">{{index}}-{{char}}</li>
</ul>

<!-- 遍历指定次数(用得少) -->
<ul>
<li v-for="(num,index) in 6" :key="index">{{index}}-{{num}}</li>
</ul>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
new Vue({
el: '#root',
data: {
person: [
{id:001,name:'a',age:18},
{id:002,name:'b',age:19},
{id:003,name:'c',age:20},
],
car: {
name: '奥迪A8',
price: '70w',
color: '黑色'
},
str: 'abcde'
}
})
key的原理

面试题: react、vue中的key有什么作用? (key的内部原理)

  1. 虚拟DOM中key的作用
    key是虚拟DOM对象的标识,当状态中的数据发生变化时,Vue会根据新数据生成新的虚拟DOM,随后Vue进行新虚拟DOM旧虚拟DOM 的差异比较,比较规则如下:
  2. 对比规则
    (1).旧虚拟DOM中找到了与新虚拟DOM相同的key:
    ①.若虚拟DOM中内容没变,直接使用之前的真实DOM!
    ②.若虚拟DOM中内容变了,则生成新的真实DOM,随后替换掉页面中之前的真实DOM。
    (2).旧虚拟DOM中未找到与新虚拟DOM相同的key:
    创建新的真实DOM,随后渲染到到页面。
  3. 用index作为key可能会引发的问题
    (1).若对数据进行逆序添加、逆序删除等破坏顺序操作:
    会产生没有必要的真实DOM更新 ==> 界面效果没问题,但效率低
    (2).如果结构中还包含输入类的DOM:
    会产生错误DOM更新 ==> 界面有问题。
  4. 开发中如何选择key?
    (1).最好使用每条数据的唯一标识作为key,比如id、手机号、身份证号、学号等唯一值。
    (2).如果不存在对数据的逆序添加、逆序则除等破坏顺序操作,仅用于渲染列表用于展示,使用index作为key是没有问题的。
1
2
3
4
5
6
7
8
9
10
11
12
13
<div id="root">
<h1>key为index</h1>
<button @click="add">添加一个d</button>
<ul>
<li v-for="(p,index) in person" :key="index">{{index}}-{{p.name}}-{{p.age}}<input type="text"></li>
</ul>

<h1>key为id</h1>
<button @click="add">添加一个d</button>
<ul>
<li v-for="(p,index) in person" :key="p.id">{{index}}-{{p.name}}-{{p.age}}<input type="text"></li>
</ul>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
new Vue({
el: '#root',
data: {
person: [
{id:001,name:'a',age:18},
{id:002,name:'b',age:19},
{id:003,name:'c',age:20},
],
},
methods: {
add(){
const p = {id:004,name:'d',age:40};
this.person.unshift(p);
}
},
})

列表过滤

1
2
3
4
5
6
7
<div id="root">
<h1>人员列表</h1>
<input type="text" v-model="keyword">
<ul>
<li v-for="(p,index) in filperson" :key="index">{{p.name}}-{{p.age}}</li>
</ul>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
new Vue({
el: '#root',
data: {
keyword: '',
person: [
{ id: 001, name: '马冬梅', age: 18, sex: '女' },
{ id: 002, name: '周冬雨', age: 19, sex: '女' },
{ id: 003, name: '周杰伦', age: 20, sex: '男' },
{ id: 003, name: '温兆伦', age: 21, sex: '男' },
],
// filperson: []
},
//监视属性写法
// watch: {
// keyword(val){
// this.filperson = this.person.filter((p)=>{
// return p.name.indexOf(val) != -1;
// })
// }
// }
//计算属性写法
computed: {
filperson() {
return this.person.filter((p) => {
return p.name.indexOf(this.keyword) != -1;
})
}
}
})

列表排序

1
2
3
4
5
6
7
8
9
10
<div id="root">
<h1>人员列表</h1>
<input type="text" 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 filperson" :key="index">{{p.name}}-{{p.age}}</li>
</ul>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
new Vue({
el: '#root',
data: {
keyword: '',
sortType: 0,
person: [
{ id: 001, name: '马冬梅', age: 18, sex: '女' },
{ id: 002, name: '周冬雨', age: 19, sex: '女' },
{ id: 003, name: '周杰伦', age: 22, sex: '男' },
{ id: 003, name: '温兆伦', age: 21, sex: '男' },
],
},
computed: {
filperson() {
let arr = this.person.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
}
}
})

数据监测

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的根数据对象 添加属性!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<div id="root">
<h1>学生信息</h1>
<button>年龄+1岁</button> <br />
<button @click="addSex">添加性别属性,默认值: 男</button> <br />
<button @click="addFriend">在列表首位添加一个朋友</button> <br />
<button @click="updateFriend">修改第一个朋友的名字为: 张三</button> <br />
<button @click="addHobby">添加一个爱好</button> <br />
<button @click="updateHobby">修改第一个爱好为: 开车</button><br />
<h3>姓名: {{student.name}}</h3>
<h3>年龄: {{student.age}}</h3>
<h3 v-if="student.sex">性别:{{student.sex}}</h3>
<h3>爱好: </h3>
<ul>
<li v-for="(h,index) in student.hobby" :key="index">{{h}}</li>
</ul>

<h3>朋友们: </h3>
<ul>
<li v-for="(f,index) in student.friends" :key="index">{{f.name}}--{{f.age}}</li>
</ul>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
new Vue({
el: '#root',
data: {
student: {
name: 'tom',
age: 18,
hobby: ['抽烟', '喝酒', '烫头'],
friends: [
{ name: 'jerry', age: 35 },
{ name: 'tony', age: 25 }
]
}
},
methods: {
addSex(){
this.$set(this.student,'sex','男');
// Vue.set(this.student,'sex','男');
},
addFriend(){
this.student.friends.unshift({name: 'tim',age:11})
},
updateFriend(){
this.student.friends[0].name = '张三'
},
addHobby(){
this.student.hobby.push('学习')
},
updateHobby(){
// this.student.hobby.splice(0,1,'开车')
// Vue.set(this.student.hobby,0,'开车');
this.$set(this.student.hobby,0,'开车');
}
}
})

收集表单数据

收集表单数据:
若:<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:输入首尾空格过滤
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<div id="root">
<form @submit.prevent="demo">
账号:<input type="text" v-model.trim="userInfo.account"> <br><br>
密码:<input type="password" v-model="userInfo.password"><br><br>
年龄:<input type="number" v-model.number="userInfo.age"><br><br>
性别:
<input type="radio" name="sex" v-model="userInfo.sex" value="male">
<input type="radio" name="sex" v-model="userInfo.sex" value="female"><br><br>
爱好:
学习<input type="checkbox" v-model="userInfo.hobby" value="study">
吃饭<input type="checkbox" v-model="userInfo.hobby" value="eat">
玩游戏<input type="checkbox" v-model="userInfo.hobby" value="playGame"><br><br>
所属校区:
<select v-model="userInfo.city">
<option value="">请选择校区</option>
<option value="beijing">北京</option>
<option value="shanghai">上海</option>
<option value="guangzhou">广州</option>
</select><br><br>
其他信息:
<textarea v-model.lazy="userInfo.other"></textarea><br><br>
<input type="checkbox" v-model="userInfo.agree">阅读并接受 <a href="javascript:;">《用户协议》</a><br><br>
<button>提交</button>
</form>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
new Vue({
el: '#root',
data: {
userInfo: {
account: '',
password: '',
age: 18,
sex: 'female',
hobby: [],
city: '',
other: '',
agree: ''
}
},
methods: {
demo() {
console.log(JSON.stringify(this.userInfo));
}
}
})

过滤器

定义:对要显示的数据进行特定格式化后再显示(适用于一些简单逻辑的处理)
语法

  1. 注册过滤器: Vue.filter(name,callback)new Vue{filters:{}}
  2. 使用过滤器:{{xxx过滤器名}}v-bind:属性 ="xxx过滤器名"

备注

  1. 过滤器也可以接收额外参数、多个过滤器也可以串联
  2. 并没有改变原本的数据,是产生新的对应的数据
1
2
3
4
5
6
7
8
9
10
11
<div id="root">
<h2>显示格式化后的时间</h2>
<!-- 计算属性实现 -->
<h3>现在是:{{fmtTime}}</h3>
<!-- methods实现 -->
<h3>现在是:{{getFmtTime()}}</h3>
<!-- 过滤器实现 -->
<h3>现在是:{{time | timeFormater}}</h3>
<!-- 过滤器实现(传参) -->
<h3>现在是:{{time | timeFormater('YYYY-MM-DD') | mySlice}}</h3>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 全局过滤器
Vue.filter('mySlice',function(value){
return value.slice(0,4);
})

new Vue({
el: '#root',
data: {
time: 1672311332525
},
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') {
return dayjs(value).format(str)
}
}
})

内置指令

我们学过的指令

我们学过的指令:

  • v-bind:单向绑定解析表达式,可简写为 :xxx
  • v-model:双向数据绑定
  • v-for:遍历数组/对象/字符串
  • v-on:绑定事件监听,可简写为@
  • v-if:条件渲染(动态控制节点是否存存在)
  • v-else:条件渲染(动态控制节点是否存存在)
  • v-show:条件渲染(动态控制节点是否展示)

v-text指令:

  1. 作用:向其所在的节点中渲染文本内容
  2. 与插值语法的区别: v-text会替换掉节点中的内容,则不会。

v-html指令:

  1. 作用:向指定节点中渲染包含html结构的内容。
  2. 与插值语法的区别:
    (1).v-html会替换掉节点中所有的内容,则不会。
    (2).v-html可以识别html结构。
  3. 严重注意: v-html有安全性问题! ! ! !
    (1).在网站上动态渲染任意HTML是非常危险的,容易导致XSS攻击。
    (2).一定要在可信的内容上使用v-html,永不要用在用户提交的内容上!

v-cloak指令(没有值) :

  1. 本质是一个特殊属性,Vue实例创建完毕并接管容器后,会删掉v-cloak届性。
  2. 使用css配合v-cloak可以解决网速慢时页面展示出的问题。

V-once指令:

  1. v-once所在节点在初次动态渲染后,就视为静态内容了
  2. 以后数据的改变不会引起v-once所在结构的更新,可以用于优化性能。

v-pre指令:

  1. 跳过其所在节点的编译过程。
  2. 可利用它跳过:没有使用指令语法、没有使用插值语法的节点,会加快编译。

自定义指令

自定义指令:

  1. 定义语法:
    (1).局部指令:new Vue({directives:{指令名:配置对象}})new Vue({directives(){}})
    (2).全局指令:Vue.directive(指令名,配置对象)Vue.directive(指令名,回调函数)
  2. 配置对象中常用的3个回调:
    (1).bind:指令与元素成功绑定时调用。
    (2).inserted:指令所在元素被插入页面时调用。
    (3).update:指令所在模板结构被重新解析时调用。
  3. 备注
    (1).指令定义时不加v-,但使用时要加v-;
    (2).指令名如果是多个单词,要使用kebab-case命名方式,不要用camelCase命名。

需求1: 定义一个v-big指令,和v-text功能类似,但会把绑定的数值放大10倍。
需求2: 定义一个v-fbind指令,和v-bind功能类似,但可以让其所绑定的input元素默认获取焦点。

1
2
3
4
5
6
7
<div id="root">
<h2>当前的n的值是:<span v-text="n"></span></h2>
<h2>放大10倍后的n值<span v-big="n"></span></h2>
<button @click="n++">点我n++</button>
<hr>
<input type="text" v-fbind:value="n">
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
new Vue({
el: '#root',
data: {
n: '1'
},
directives: {
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
element.focus()
}
}
}
})

生命周期

生命周期:

  1. 又名:生命周期回调函数、生命周期函数、生命周期钩子。
  2. 是什么: Vue在关键时刻帮我们调用的一些特殊名称的函数。
  3. 生命周期函数的名字不可更改,但函数的具体内容是程序员根据需求编写的。
  4. 生命周期函数中的this指向是vm或组件实例对象。
1
2
3
4
<div id="root">
<h2 :style="{opacity}">学习vue</h2>
<button @click="stop()">点击暂停</button>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
new Vue({
el: '#root',
data: {
opacity: 1
},
methods: {
stop(){
this.$destroy()
}
},
mounted(){
this.timer = setInterval(() => {
this.opacity -= 0.01;
if(this.opacity <= 0) this.opacity = 1;
},20)
},
beforeDestroy() {
clearInterval(this.timer)
}
})

常用的生命周期钩子:

  1. mounted:发送ajax请求、启动定时器、绑定自定义事件、订阅消息等初始化操作。
  2. beforeDestroy:清除定时器、解绑自定义事件、取消订阅消息等收尾工作。

关于销毁Vue实例

  1. 销毁后借助Vue开发者工具看不到任何信息。
  2. 销毁后自定义事件会失效,但原生DOM事件依然有效。
  3. 一般不会在beforeDestroy操作数据,因为即便操作数据,也不会再触发更新流程了。