更新vue的data中的元素,vue更新错误

更新vue的data中的元素,vue更新错误

一、总结

一句话总结:

解决方式:用【深拷贝】可以解决,直接对vue操作的【一级数据进行深拷贝】,然后修改
问题思考:估计vue基于数据的更新【只检查一级数据的地址是否改变】,如果地址改变才基于这个更新
错误方式:如果这样更新:【vue看到的数据地址根本没有改变】:this.blog_entries_logs[index]['open_detail']=!this.blog_entries_logs[index]['open_detail'];


具体解决:

//点击博客引入详情操作
toggle_blogEntry_detail:function(index){
    let new_data =  JSON.parse(JSON.stringify( this.blog_entries_logs));
    new_data[index]['open_detail']=!new_data[index]['open_detail'];
    this.blog_entries_logs=new_data;
},

二、更新vue的data中的元素,vue更新错误

1、错误现象

核心错误代码:

//点击博客引入详情操作
toggle_blogEntry_detail:function(index){
    this.blog_entries_logs[index]['open_detail']=!this.blog_entries_logs[index]['open_detail'];
},

循环:

<template v-for="(blog_entries_log,index) in blog_entries_logs">

事件绑定:

<div @click.stop="toggle_blogEntry_detail(index)" style="font-size: 20px;cursor: pointer;">

v-show显示:

<tr class="blog_load_tr" v-show="blog_entries_log.open_detail">

完整vue代码:

<script>
    blog_entry_box_vue=new Vue({
        el:'#blog_entry',
        data:{
            blog_entries_logs:window.blog_entries_logs,
        },
        beforeMount:function(){
            //console.log('beforeMount');
            //用于预处理数据
            this.init_data();
        },
        methods:{
            click_1:function(){
                this.open=!this.open;
            },
            //初始化数据
            init_data:function(){
                for(let i=0;i<this.blog_entries_logs.length;i++) {
                    this.blog_entries_logs[i]['open_detail']=true;
                }
                console.log('init_data');
            },
            //点击博客引入详情操作
            toggle_blogEntry_detail:function(index){

                this.blog_entries_logs[index]['open_detail']=!this.blog_entries_logs[index]['open_detail'];
                console.log(this.blog_entries_logs[index]['open_detail']);
                console.log(index);
                console.log(this.blog_entries_logs);
            },
            time_format_toDay:function (ts) {
                ts=ts*1000;
                return moment(ts).format('YYYY-MM-DD');
            },
            time_format_toSecond:function (ts) {
                ts=ts*1000;
                return moment(ts).format('YYYY-MM-DD HH:mm:ss');
            }
        }
    });
</script>

2、解决方案

解决方式:
用【深拷贝】可以解决,直接对vue操作的【一级数据进行深拷贝】,然后修改

问题思考:
估计vue基于数据的更新只检查一级数据的地址是否改变,如果地址改变才基于这个更新
如果这样更新:【vue看到的数据地址根本没有改变】:this.blog_entries_logs[index]['open_detail']=!this.blog_entries_logs[index]['open_detail'];

具体解决:

//点击博客引入详情操作
toggle_blogEntry_detail:function(index){
    let new_data =  JSON.parse(JSON.stringify( this.blog_entries_logs));
    new_data[index]['open_detail']=!new_data[index]['open_detail'];
    this.blog_entries_logs=new_data;
},

错误位置的界面:

 
原文地址:https://www.cnblogs.com/Renyi-Fan/p/14261551.html