代码改变世界

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

  龙恩0707  阅读(23000)  评论(1编辑  收藏  举报

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>
复制代码

查看效果

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
历史上的今天:
2013-08-27 如何使左侧固定宽度右侧自适应。
2013-08-27 如何用css实现"等高布局"。
2013-08-27 JS常见的小代码
2013-08-27 Jquery弹窗组件
2013-08-27 javascript 深度克隆对象
点击右上角即可分享
微信分享提示