2022
我们一起努力

vue中更改数组中属性在页面中不生效怎么办

这篇文章将为大家详细讲解有关vue中更改数组中属性在页面中不生效怎么办,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

问题描述:

使用vue的方法获取了数组数据,获取数据后为每个数据增加edit属性,初始值均为false,其目的是为了当点击列表中的编辑按钮时,控制保存与不保存的按钮的出现与消失,结果当更改数组中的edit属性后,页面并没有如预期的那样当edit为true时页面显示更改状态,当edit为false时为不更改状态

解决方案:

edit是在通过post方法获取数据后增加到vue的data数据中的属性,一开始我的做法先将接收到的数据赋值到vue的data中,再对vue的data中的数据增加edit属性,这样在改变edit的之后,虽然在js中使用console.log可以看到该值已经发生变化,但页面中的data值并没有发生变化。

vue中更改数组中属性在页面中不生效怎么办

正确的做法应该是先为接收到的数据初始化edit属性,再将处理后的数据赋值给vue的data。

代码如下

<tbody>
     <tr v-for="(book,index) in bookList">
      <td>
       <span v-on:click="book.edit=true" v-show=" !book.edit">{{book.orderIndex}}</span> //如果edit属性为false,则该span出现
       <input v-show="book.edit" /> //如果edit属性为true,则该input出现
      </td>
      <td>
       <a v-show="book.edit" v-on:click="book.edit=false" class="btn btn-primary btn-sm"> //如果edit属性为true,出现不保存(x)按钮
        <i class="glyphicon glyphicon-remove" aria-hidden="true"></i>
</a>
       <a v-show="book.edit" v-on:click="save(book)" class="btn btn-primary btn-sm"> //如果edit属性为true,出现保存(√)按钮
        <i class="glyphicon glyphicon-ok" aria-hidden="true"></i>
       </a>
      </td>
      
     </tr>
    </tbody>

<script>

var politics = new Vue({

el:"#politics",

data:{

bookList:[]

},

methods:{

getBookList: function (offset, limit, CatalogueID, searchKey, resId) {
    this.limit = limit;
    this.offset = offset;
    this.CatalogueID = CatalogueID;
    this.searchKey = searchKey;
    this.resId = resId;
    this.$http.get("/BookAdmin/getBookList?offset=" + this.offset + "&limit=" + this.limit + "&CatalogueID=" + this.CatalogueID + "&searchKey=" + this.searchKey+"&resId="+this.resId)
     .then(function (resp) {
      resp.data.books.forEach(function (o, i) {
       o.edit = false;
      })
      this.bookList = resp.data.books; // 赋值必须写在属性初始化的后面,否则改edit不能使页面属性变化
      this.bookTotalCount = resp.data.totalCount;
      var pageNo = this.offset / this.limit + 1;
      var totalPage = Math.ceil(this.bookTotalCount / this.limit);
      
      divpager(pageNo, totalPage, this.bookTotalCount, this.CatalogueID, this.searchKey, this.resId);
     })
   }

}

})


</script>

关于“vue中更改数组中属性在页面中不生效怎么办”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

赞(0)
文章名称:《vue中更改数组中属性在页面中不生效怎么办》
文章链接:https://www.fzvps.com/82984.html
本站文章来源于互联网,如有侵权,请联系管理删除,本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。
图片版权归属各自创作者所有,图片水印出于防止被无耻之徒盗取劳动成果的目的。

评论 抢沙发

评论前必须登录!