首页 > 语言 > JavaScript > 正文

详解vue 实例方法和数据

2024-05-06 15:25:17
字体:
来源:转载
供稿:网友

1.vm.$set

问题描述:

如何在不通过循环数据给list数据添加一个showMore属性,并且在moreFun中改变这个新增属性的值,并实现双向绑定?

<template> <div id="app">  <div class="demo">   <ul>    <template v-for="(v,index) in list">     <li>{{v.name}}</li>     <div v-show="!v.showMore">      <button @click="moreFun(index)">展示更多</button>     </div>    </template>   </ul>  </div> </div></template><script>export default { name: 'app', data() {  return {   list: [{    name: '小颖'   }, {    name: '仔仔'   }, {    name: '黑妞'   }, {    name: '土豆'   }]  } }, methods: {  moreFun(index) {   console.log(this.list);  } }}</script><style>#app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px;}</style>

一开始小颖并不知道怎么做,而且小颖觉得               

 <div v-show="!v.showMore">      <button @click="moreFun(index)">展示更多</button>     </div>

这段代码肯定会报错,然而当小颖写上后发现,并没有,后来那位帅锅告诉我,看看vue的  vm.$set     小颖看后将moreFun方法写为:

 moreFun(index) {   this.$set(this.list[index], 'showMore', true);   console.log(this.list);  }

然后就达到小颖想要的结果啦。小颖当时遇到的问题类似于这样的:

<template> <div id="app">  <div class="demo">   <ul>    <template v-for="(v,index) in list">     <li>{{v.name}}</li>     <div v-show="!v.showMore">      <button @click="moreFun(index)">展示更多</button>     </div>    </template>   </ul>  </div> </div></template><script>export default { name: 'app', data() {  return {   list: [{    name: '小颖'   }, {    name: '仔仔'   }, {    name: '黑妞'   }, {    name: '土豆'   }]  } }, mounted: function() {  this.list.forEach(function(element, index) {   element.showMore = false;  }); }, methods: {  moreFun(index) {   this.list[index].showMore = true;   console.log(this.list);  } }}</script><style>#app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px;}</style>

问题:当执行完moreFun方法后,虽然list中的showMore属性的值变成了true,但是

<div v-show="!v.showMore"> <button @click="moreFun(index)">展示更多</button> </div>            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选