vue.js - vue的一个新数据和原始数据问题

查看:103
本文介绍了vue.js - vue的一个新数据和原始数据问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

完整代码是这样

我将父组件传入的data 放到 rebuildData中
用rebuilData来渲染数据

methods里都是操作rebuildData

为什么最后
data会和rebuilData一样被改变

<template>
  <Row class="vm-progress vm-panel">
    <Row type="flex"  align="middle" justify="space-between" class="panel-heading">
      {{ title }}
      <Radio-group v-model="order" type="button" size="large" @on-change="handleSortData">
        <Radio label="0">默认</Radio>
        <Radio label="1">正序</Radio>
        <Radio label="-1">倒序</Radio>
      </Radio-group>
    </Row>
    <table> 
      <tbody> 
        <tr v-for="(item, index) in rebuildData">
          <td>  
           {{ index | indexPlus }}
          </td>
          <td>  
            {{ item.name }}
          </td>
          <td v-if="item.tags">  
            <Tag v-for="item in item.tags">{{ item }}</Tag>
          </td>
          <td>  
            <Progress :percent="item.value" status="active"></Progress>
          </td>
        </tr>
      </tbody>
    </table>
  </Row>
</template>
<script>
  export default {
    name: 'VmUserPreview',
    props: {
      title: {
        type: String,
        default: '工作进度'
      },
      data: {
        type: Array,
        default: function () {
          return [
            {
              name: 'JesseLuo',
              tags: ['很帅', '逗比', '可以'],
              value: 100
            }
          ]
        }
      }
    },
    data: function () {
      return {
        order: '0',
        rebuildData: this.data
      }
    },
    filters: {
      indexPlus: function (value) {
        return ++value
      }
    },
    methods: {
      sortData: function (data, type) {
        if (type === 1) {
          data.sort((a, b) => {
            return a.value - b.value
          })
        } else if (type === -1) {
          data.sort((a, b) => {
            return b.value - a.value
          })
        }
      },
      handleSortData: function () {
        if (this.order === '0') {
          this.rebuildData = this.data
        } else if (this.order === '1') {
          this.sortData(this.rebuildData, 1)
        } else if (this.order === '-1') {
          this.sortData(this.rebuildData, -1)
        }
        console.log(this.data[0].value)
        console.log(this.rebuildData[0].value)
      }
    }
  }
</script>

解决方案

从原始数组中拷贝一份新的, 分清值类型与引用类型

这篇关于vue.js - vue的一个新数据和原始数据问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆