详解vue 实例方法和数据

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>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/1312.html