学习vue时,当我们有一个列表,我们想让列表进行动态更新时,就要用到数组变化侦测技术。方法分为两个大类,一种是改变<ul>标签的结构,造成列表的变更,另一种是替换一个数组,这种方法不会自动使<ul>标签变更!
一.变更方法
Vue 能够侦听响应式数组的变更方法,并在它们被调用时触发相关的更新。这些变更方法包括
push(),pop(),shift(),unshift(),splice(),sort(),reverse()
代码演示:
<template>
<h3>数组变化侦听</h3>
<button @click="addListHandle">添加数据</button>
<ul>
<li v-for="(item,index) of names" :key="index">{{ item }}</li>
</ul>
</template>
<script>
export default{
data(){
return{
names:["name","age","string"]
}
},
methods:{
addListHandle(){
this.names.push("nihaoCSDN")
}
}
}
</script>
运行展示:
二.替换一个数组
变更方法,顾名思义,就是会对调用它们的原数组进行变更,相对地,也有一些不可变(immutable)方法,是直如 filter(),concat() 和slice(),这些都不会更改原数组,而总是返回一个新数组。当遇到的是非变更方法时,我们需要将旧的数组替换为新的
代码演示:
<template>
<h3>数组变化侦听</h3>
<button @click="addListHandle">添加数据</button>
<ul>
<li v-for="(item, index) of names" :key="index">{{ item }}</li>
</ul>
</template>
<script>
export default {
data() {
return {
names: ["name", "age", "string"]
}
},
methods: {
addListHandle() {
this.names.concat(["nihao新数组"])
console.log(this.names.concat(["nihao新数组"]));
}
}
}
</script>
运行结果:
如果想把添加的数据渲染到<ul>标签上面
需要在方法里面加入一行代码
this.names=this.names.concat("nihao新数组")
结果演示: