Vue 改变数组中对象的属性不重新渲染View的解决方案

在解决问题之前,我们先来了解下 vue响应性原理: Vue最显著的一个功能是响应系统-- 模型只是一个普通对象,修改对象则会更新视图。
受到javascript的限制,Vue不能检测到对象属性的添加或删除,因为vue在初始化实列时将属性转为getter/setter,所以属性必须在data对象上才能让vue转换它。
但是vue可以使用 Vue.set(object, key, value)方法将响应属性添加到嵌套的对象上:如下代码:

Vue.set(obj, ‘_isHover‘, true);

或者可以使用vm.$set的实列方法,也是Vue.set方法的别名:

this.$set(obj, ‘_isHover‘, false);

问题: 页面上多个item项, 当我鼠标移动上去的时候,我想在该数组中的对象添加一个属性 isHover=true, 当鼠标移出的时候,我想让该属性变为 isHover=false,然后希望改变对象的属性的时候让其重新渲染view层,重新执行rowClasses方法,然后该方法会判断 isHover是否等于true,如果为true的话,让其增加一个类名。
代码如下:

<!DOCTYPE html>
<html>
  <head>
    <title>演示Vue</title>
    <style>
      * {margin: 0; padding: 0;}
      ul, li {list-style: none;}
      #app {width: 800px; margin: 20px auto; border:1px solid #ccc; border-bottom: none;}
      #app li {height: 32px; line-height: 32px; border-bottom: 1px solid #ccc;}
      #app li.bgColor {background-color: red;}
    </style>
  </head>
  <body>
    <div id=‘app‘>
      <ul>
        <li
          v-for="(item, index) in items"
          @mouseenter.stop="handleMouseIn(index)"
          @mouseleave.stop="handleMouseOut(index)"
          :class="rowClasses(index)"
        >
          <span>{{item.name}}</span>
        </li>
      </ul>
    </div>
  </body>
  <script src="https://tugenhua0707.github.io/vue/vue1/vue.js"></script>
  <script type="text/javascript">
    new Vue({
      el: ‘#app‘,
      data: {
        items: [
          {name: ‘kongzhi‘},
          {name: ‘longen‘},
          {name: ‘tugenhua‘}
        ]
      },
      computed: {

      },
      methods: {
        rowClasses (index) {
          return [
            {
              [`bgColor`]: this.$data.items[index] && this.$data.items[index]._isHover
            }
          ]
        },
        handleMouseIn(index) {
          if (this.$data.items[index]._isHover) {
            return;
          }
          console.log(111); // 可以执行到
          this.$data.items[index]._isHover = true;
        },
        handleMouseOut(index) {
          this.$data.items[index]._isHover = false;
        }
      }
    });
  </script>
</html>

查看效果

可以看到鼠标移动上去的时候 没有效果。

解决的方案如下:

1. 使用 Object.assign

鼠标移动上去的时候 代码可以改成如下:

this.$data.items[index]._isHover = true;
this.$data.items = Object.assign({}, this.$data.items);

鼠标移出的时候,代码改成如下:

this.$data.items[index]._isHover = false;
this.$data.items = Object.assign({}, this.$data.items);

代码如下:

<!DOCTYPE html>
<html>
  <head>
    <title>演示Vue</title>
    <style>
      * {margin: 0; padding: 0;}
      ul, li {list-style: none;}
      #app {width: 800px; margin: 20px auto; border:1px solid #ccc; border-bottom: none;}
      #app li {height: 32px; line-height: 32px; border-bottom: 1px solid #ccc;}
      #app li.bgColor {background-color: red;}
    </style>
  </head>
  <body>
    <div id=‘app‘>
      <ul>
        <li
          v-for="(item, index) in items"
          @mouseenter.stop="handleMouseIn(index)"
          @mouseleave.stop="handleMouseOut(index)"
          :class="rowClasses(index)"
        >
          <span>{{item.name}}</span>
        </li>
      </ul>
    </div>
  </body>
  <script src="https://tugenhua0707.github.io/vue/vue1/vue.js"></script>
  <script type="text/javascript">
    new Vue({
      el: ‘#app‘,
      data: {
        items: [
          {name: ‘kongzhi‘},
          {name: ‘longen‘},
          {name: ‘tugenhua‘}
        ]
      },
      computed: {

      },
      methods: {
        rowClasses (index) {
          return [
            {
              [`bgColor`]: this.$data.items[index] && this.$data.items[index]._isHover
            }
          ]
        },
        handleMouseIn(index) {
          if (this.$data.items[index]._isHover) {
            return;
          }
          console.log(111); // 可以执行到
          this.$data.items[index]._isHover = true;
          this.$data.items = Object.assign({}, this.$data.items);
        },
        handleMouseOut(index) {
          this.$data.items[index]._isHover = false;
          this.$data.items = Object.assign({}, this.$data.items);
        }
      }
    });
  </script>
</html>

查看效果

2. 使用Vue.set(object, key, value)方法将响应属性添加到嵌套的对象上。

鼠标移动上去的时候 代码可以改成如下:

this.$set(this.$data.items[index], ‘_isHover‘, true);

鼠标移出的时候,代码改成如下:

this.$set(this.$data.items[index], ‘_isHover‘, false);

所有的代码如下:

<!DOCTYPE html>
<html>
  <head>
    <title>演示Vue</title>
    <style>
      * {margin: 0; padding: 0;}
      ul, li {list-style: none;}
      #app {width: 800px; margin: 20px auto; border:1px solid #ccc; border-bottom: none;}
      #app li {height: 32px; line-height: 32px; border-bottom: 1px solid #ccc;}
      #app li.bgColor {background-color: red;}
    </style>
  </head>
  <body>
    <div id=‘app‘>
      <ul>
        <li
          v-for="(item, index) in items"
          @mouseenter.stop="handleMouseIn(index)"
          @mouseleave.stop="handleMouseOut(index)"
          :class="rowClasses(index)"
        >
          <span>{{item.name}}</span>
        </li>
      </ul>
    </div>
  </body>
  <script src="https://tugenhua0707.github.io/vue/vue1/vue.js"></script>
  <script type="text/javascript">
    new Vue({
      el: ‘#app‘,
      data: {
        items: [
          {name: ‘kongzhi‘},
          {name: ‘longen‘},
          {name: ‘tugenhua‘}
        ]
      },
      computed: {

      },
      methods: {
        rowClasses (index) {
          return [
            {
              [`bgColor`]: this.$data.items[index] && this.$data.items[index]._isHover
            }
          ]
        },
        handleMouseIn(index) {
          if (this.$data.items[index]._isHover) {
            return;
          }
          console.log(111); // 可以执行到
          this.$set(this.$data.items[index], ‘_isHover‘, true);
        },
        handleMouseOut(index) {
          this.$set(this.$data.items[index], ‘_isHover‘, false);
        }
      }
    });
  </script>
</html>

查看效果

时间: 2024-08-06 17:46:49

Vue 改变数组中对象的属性不重新渲染View的解决方案的相关文章

利用KVC的方式更方便地获取数组中对象的属性的最值平均值等

直接上代码 输出结果也在相应的代码里标注出来了 1 //main.m文件 2 #import <Foundation/Foundation.h> 3 #import "Student.h" 4 5 int main(int argc, const char * argv[]) { 6 @autoreleasepool { 7 8 NSMutableArray <Student *> *_studentArrM; 9 NSMutableArray <Stud

关于vue数组中对象属性变更页面没重新渲染的问题

前段时间做开发的时候用mqtt监听了服务端信息,推送过来的数据要变更数组里面的对象的数据,修改好后但是页面并没有更新,因为javascript机制,vue并不能检测到数组变化,也是查阅知道了$set()函数, 具体用法: arr.$set(index, { name : value }), index: 索引,name: 数组中对象的属性名, value: 要赋给属性的值 this.footerList.$set(i, { siteId : monitorSiteData[j].siteId,

[转] 小程序修改数组中对象的某个值或者修改对象值

小程序中获取当前data定义的值,用this.data.xxx setData的时候要修改的值是不需要加this.data.xxx的,直接xxx, 一般直接修改data的值直接修改,修改数组中对象的值或者对象的属性值都要先转为字符串再加中括号,如果有变量可以用ES6的模版字符串反单引号或者字符串拼接一下. Page({ data: { currentValue:"aa", todoLists:[ { detail:"", date:"", loc

动态数组,数组初始化,数组内存释放,向数组中添加一个元素,向数组中添加多个元素,数组打印,顺序查找,二分查找,查找数组并返回地址,冒泡排序,改变数组中某个元素的值,删除一个数值,删除所有,查找含有

 1定义接口: Num.h #ifndef_NUM_H_ #define_NUM_H_ #include<stdio.h> #include<stdlib.h> /************************************************************************/ /*数组的结构体类型                                                    */ /*******************

java 对list中对象按属性排序

实体对象类 --略 排序类----实现Comparator接口,重写compare方法 package com.tang.list; import java.util.Comparator; public class Mycompera implements Comparator<Student> { @Override    public int compare(Student o1, Student o2) {        if (o1.getSid() > o2.getSid()

js遍历数组重复值和数组中对象重复值

数组去除重复值: arr.indexOf() 方法返回某个指定字符串值再字符中首次出现的位置, 如果数组中没有则返回-1 var arr=[2,8,5,0,5,2,6,7,2]; function unique1(arr){ var result=[]; for (var i = 0; i < arr.length; i++) { if(hash.indexOf(arr[i])==-1){ resule.push(arr[i]); } } return result; } 数组中对象去除的重复值

vue数组中对象属性变化页面不渲染问题

做checkbox多选功能的时候遇到了一个坑,逻辑怎么看都对,但是就是有bug,最后发现数组那里值变了页面勾选没有重新渲染. 换了关键词搜索找到了相关方法. 其实之前读文档教程的时候看到过这里,但是只有真的使用之后才会有最直接的感触. ------------------------------------------- 数组更新检测 变异方法 Vue 包含一组观察数组的变异方法,所以它们也将会触发视图更新.这些方法如下: push() pop() shift() unshift() splic

递归找出数组中对象属性为某个值的选项,不改变原数组

arr数组每一项为一个对象,并且每一项可能有children属性,其值为同它本身一样的数组,要求找到数组中checked==true的值(前提:如果其子元素checked==true,那么父级的checked一定为true) 这里的逻辑跟该自定义组件相似:http://www.cnblogs.com/XHappyness/p/7451611.html findValue(arr) { let newArr= [].concat(arr);//把值赋值给一个新数组,而不是赋值引用:如果直接 let

JavaScript中对象的属性

原文:http://www.2ality.com/2012/10/javascript-properties.html JavaScript中有三种不同类型的属性:命名数据属性(named data properties),命名访问器属性(named accessor properties)以及内部属性(internal properties). 命名数据属性 这种属性就是我们通常所用的"普通"属性,它用来将一个字符串名称映射到某个值上.比如,下面的对象obj有一个名为字符串"