javascript - vue 如何判斷v-for里的某個(gè)值發(fā)送變化
問(wèn)題描述
先貼代碼,直接粘貼過(guò)去就能看效果
<!DOCTYPE html><html><head> <meta charset='UTF-8'> <title></title> <script src='https://cdn.bootcss.com/vue/2.3.4/vue.min.js'></script> <style>* { margin: 0; padding: 0;}.bg { width: 300px; height: 400px; position: absolute; top: 50px; left: 100px; border: 1px solid #ccc;}.bg ul li { margin-bottom: 50px;} </style></head><body><p><p class='bg'> <ul><li v-for='item of list' :key='item.id'> <h2>{{ item.name }}</h2> <span v-show='false'>我出現(xiàn)了</span></li> </ul></p><script>const app = new Vue({ el: ’.bg’, data () {return { list: [{ id: 0, name: ’李四’, number: 0},{ id: 1, name: ’張三’, number: 0},{ id: 2, name: ’王五’, number: 0}, ]} }})</script></p></body></html>
我想監(jiān)聽(tīng)list 下面的number 是否發(fā)生變化,或者大于現(xiàn)在的number。如果number發(fā)生變化了, h2下面的span 就會(huì)出現(xiàn)。 然后 1秒消失。
但是沒(méi)想到怎么去做。 (注意: 哪個(gè)number變化就哪個(gè)span出現(xiàn)。 不是所有都出現(xiàn)。)
問(wèn)題解答
回答1:不錯(cuò),應(yīng)該使用 watch
應(yīng)該分拆使用組建,我想原汁原味的Vue寫法應(yīng)該如此:
Vue.component(’list-view’, { props: [’item’], data() { return { is_show: false } }, watch: { ’item.number’: function(newN, oldN) { this.is_show = newN > oldN; }, is_show: function(newStatus) { if (newStatus) {setTimeout(() => this.is_show = false, 1000); } } }, template: ` <li><h2 v-text='item.name'></h2> <span v-show='is_show'>我出現(xiàn)了</span> </li>`});const app = new Vue({ el: ’.bg’, data() { return { list: [{id: 0,name: ’李四’,number: 0 }, {id: 1,name: ’張三’,number: 0 }, {id: 2,name: ’王五’,number: 0 }, ] } }, mounted() { //測(cè)試用的 setTimeout(() => { this.$set(this.list[0], ’number’, 1); }, 1000); setTimeout(() => { this.$set(this.list[1], ’number’, 1); }, 2000); setTimeout(() => { this.$set(this.list[2], ’number’, 1); }, 3000); }});
<p> <p class='bg'> <ul> <list-view v-for='item in list' :item='item' :key='item.id'> </list-view> </ul> </p></p>
可以到 https://jsfiddle.net/1rb586dr/2/ 體驗(yàn)
回答2:你可以使用watch()屬性
api文檔:vue-vatch
希望可以幫到你,如果還不懂再@我
相關(guān)文章:
1. mysql - 表名稱前綴到底有啥用?2. 致命錯(cuò)誤: Class ’appfacadeTest’ not found3. 老師們php,插入數(shù)據(jù)庫(kù)mysql,都是空的,要怎么解決4. 求大神支招,php怎么操作在一個(gè)html文件的<head>標(biāo)記內(nèi)添加內(nèi)容?5. php點(diǎn)贊一天一次怎么實(shí)現(xiàn)6. 怎么php怎么通過(guò)數(shù)組顯示sql查詢結(jié)果呢,查詢結(jié)果有多條,如圖。7. PHP類屬性聲明?8. sql語(yǔ)句 - 如何在mysql中批量添加用戶?9. phpstady在win10上運(yùn)行10. 在應(yīng)用配置文件 app.php 中找不到’route_check_cache’配置項(xiàng)
