哪些数组方法是响应式的?
Vue中包含了一组观察数组编译的方法,使用它们改变数组也会触发视图的更新。
push(), 在数组最后面添加元素
pop(),删除数组中的最后一个元素
shift(), 删除数组中的第一个元素
unshift(), 在数组最前面添加元素
splice(), 删除元素/插入元素/替换元素
1.删除元素: 第二个参数传入你要删除几个元素(如果没有传,就删除后面所有的元素)
2.替换元素: 第二个参数, 表示我们要替换几个元素, 后面是用于替换前面的元素
3.插入元素: 第二个参数, 传入0, 并且后面跟上要插入的元素
sort(),数组排序
reverse(),反转数据
Vue提供的set方法,通过数组下标动态更改数据
set(要修改的对象, 索引值, 修改后的值)
Vue.set(this.letters, 0, ‘bbbbbb’)
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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body>
<div id="app"> <ul> <li v-for="item in letters">{{item}}</li> </ul> <button @click="btnClick">按钮</button> </div>
<script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { letters: ['a', 'b', 'c', 'd'] }, methods: { btnClick() {
this.letters.splice(1, 3, 'm', 'n', 'l', 'x')
} } })
</script>
</body> </html>
|
登录切换小案例
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 40 41 42 43 44 45 46 47 48 49 50
| <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=
, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<span v-if="isUser">
<label for="username" >{{username}}</label>
<input type="text" id="username" placeholder="用户账号" key="username"> </span> <span v-else> <label for="email" >{{email}}</label> <input type="text" id="email" placeholder="用户邮箱" key="email"> </span> <button @click="isUser =! isUser">切换类型</button> </div> <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> <script> const app = new Vue({ el: "#app", data :{ username: "用户账号:", email: "邮箱账号:", isUser: true } })
</script>
</body>
</html>
|
案例小问题
如果我们在有输入内容的情况下,切换了类型,我们会发现文字依然显示之前的输入的内容。但是按道理讲,我们应该切换到另外一个
input元素中了。在另一个input元素中,我们并没有输入内容。为什么会出现这个问题呢?
问题解答:
这是因为Vue在进行DOM渲染时,出于性能考虑,会尽可能的复用已经存在的元素,而不是重新创建新的元素。
在上面的案例中,Vue内部会发现原来的input元素不再使用,直接作为else中的input来使用了。
解决方案:
如果我们不希望Vue出现类似重复利用的问题,可以给对应的input添加key
并且我们需要保证key的不同
当前字体点击后变色
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
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .active{ color: red; } </style> </head> <body> <div id="app"> <ul> <li v-for="(item,index) in movies" :class= "{active: currentIndex === index}" @click= "fun(index)" >{{item}}</li> </ul> </div> <script src='https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js'></script> <script> const app = new Vue({ el: '#app', data :{ movies: ["长津湖","战狼","湄公河"], currentIndex: 0 }, methods:{ fun(index){ this.currentIndex = index; } } }) </script> </body> </html>
|