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>
新聞熱點
疑難解答
圖片精選