Vue学习教程-11数组变化监测

文章目录

  • 前言
  • 一、vue侦听响应数组变更方法
  • 二、使用Vue.set或者this.$set
  • 三、替换数组
  • 总结


前言

在Vue中,数组变化监测是其响应式系统的一个重要特性。Vue 2.x版本中,当使用Vue.set或者this.$set,或者在初始化时就声明好数组的每个元素或者调用数组方法,可以确保数组的变更能够被Vue检测到并触发视图的更新。然而,在某些情况下,直接通过索引修改数组元素,例如array[index] = newValue,Vue无法检测到这些变化,从而导致视图不更新。


一、vue侦听响应数组变更方法

Vue能够侦听响应式数组的变更方法,并在它们被调用时触发相关的更新。这些变更方法包括:

  • push():在数组末尾添加一个或多个元素,并返回新的长度
  • pop():移除数组的最后一个元素,并返回该元素
  • shift():移除数组的第一个元素,并返回该元素
  • unshift():在数组开头添加一个或多个元素,并返回新的长度
  • splice():移除或者替换已存在的元素和/或添加新的元素
  • sort():对数组的元素进行排序,并返回对相同数组的引用
  • reverse():反转数组中的元素,并返回同一数组的引用
<head>
 	<meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数组变化监测title>
    
<script type="text/javascript" src="../js/vue.js">script>
head>
<body>
    <div id="root">
         <h2>数组变更方法h2>
         <p>{{arr}}p>
         <button @click="arrPush">pushbutton>
         <button @click="arrPop">popbutton>
         <button @click="arrUnshift">unshiftbutton>
         <button @click="arrShift">shiftbutton>
         <button @click="arrSplice">splicebutton>
         <button @click="arrSort">sortbutton>
         <button @click="arrReverse">reversebutton>
    div>
body>
<script>
    Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
    // 创建vm实例
    const vm = new Vue({
         el:'#root',
         data(){
              return {
                   arr:[1,2,3,4,5],
              }
         },
         methods: {
              arrPush(){
                   this.arr.push(6);

              },
              arrPop(){
                   this.arr.pop()
                },
              arrUnshift(){
                   this.arr.unshift(11)

              },
              arrShift(){
                   this.arr.shift();
              },
              arrSplice(){
                   this.arr.splice(1,0,33,44)
              },
              arrSort(){
                   this.arr.sort((a,b)=>{return b-a})
              },
              arrReverse(){
                   this.arr.reverse()
              }
         },
         
    })
script>

二、使用Vue.set或者this.$set

在Vue修改数组中的某个元素也可以通过使用Vue.set或者this.$set

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数组变化监测title>
    
<script type="text/javascript" src="../js/vue.js">script>
head>
<body>
    <div id="root">
         <h2>使用Vue.set或vm.$set变更数组h2>
         <button @click="updateHobby">修改第一个爱好为:开车button> <br/>
         <h3>姓名:{{student.name}}h3>
         <h3>年龄:{{student.age}}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>
    
body>
<script>
    Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
    // 创建vm实例
    const vm = new Vue({
         el:'#root',
         data(){
              return {
                   arr:[1,2,3,4,5],
                   student:{
				name:'tom',
				age:18,
				hobby:['抽烟','喝酒','烫头'],
				friends:[
					{name:'jerry',age:35},
					{name:'tony',age:36}
				]
			}
              }
         },
         methods: {
              updateHobby(){
                   // this.student.hobby.splice(0,1,'开车')//使用splice方法也能更新
                   // Vue.set(this.student.hobby,0,'开车')//奏效
                   this.$set(this.student.hobby,0,'开车')//奏效
			},
         },
         
    })
script>

三、替换数组

变更方法,顾名思义,就是会对调用它们的原数组进行变更。相对地,也有一些不可变的方法,例如filter()、concat() 和slice(),这些都不会更改原数组,而总是返回一个新数组。当遇到的是非变更方法时,我们需要将旧的数组替换为新的数组

<head>
   <meta charset="UTF-8" />
   <meta name="viewport" content="width=device-width, initial-scale=1.0" />
   <title>数组变化监测title>
   
   <script type="text/javascript" src="../js/vue.js">script>
 head>
<body>
   <div id="root">
     <h2>生产新的数组h2>
     <button @click="removeSmoke">过滤掉爱好中的抽烟button> <br />
   div>
 body>
<script>
   Vue.config.productionTip = false; //阻止 vue 在启动时生成生产提示。
   // 创建vm实例
   const vm = new Vue({
     el: "#root",
     data() {
       return {
         student: {
           name: "tom",
           age: 18,
           hobby: ["抽烟", "喝酒", "烫头"],
           friends: [
             { name: "jerry", age: 35 },
             { name: "tony", age: 36 },
           ],
         },
       };
     },
     methods: {
       removeSmoke() {
         // 注意使用filter()并没有更改原数组hobby,所以需要赋值覆盖原数组
         this.student.hobby = this.student.hobby.filter((h) => {
           return h !== "抽烟";
           console.log(this.student.hobby)
         });
       },
     },
   });
 script>

总结

在Vue修改数组中的某个元素一定要用如下方法:

  1. 使用这些API:push()、pop()、shift()、unshift()、splice()、sort()、reverse()
  2. Vue.set() 或 vm.$set()
  3. 特别注意:Vue.set() 和 vm.$set() 不能给vm 或 vm的根数据对象 添加属性!!!

你可能感兴趣的:(vue.js,学习,javascript)