javascript - vue 如何判斷v-for里的某個值發送變化
問題描述
先貼代碼,直接粘貼過去就能看效果
<!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'>我出現了</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>
我想監聽list 下面的number 是否發生變化,或者大于現在的number。如果number發生變化了, h2下面的span 就會出現。 然后 1秒消失。
但是沒想到怎么去做。 (注意: 哪個number變化就哪個span出現。 不是所有都出現。)
問題解答
回答1:不錯,應該使用 watch
應該分拆使用組建,我想原汁原味的Vue寫法應該如此:
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'>我出現了</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() { //測試用的 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/ 體驗
回答2:你可以使用watch()屬性
api文檔:vue-vatch
希望可以幫到你,如果還不懂再@我
相關文章:
1. python - 獲取到的數據生成新的mysql表2. javascript - js 對中文進行MD5加密和python結果不一樣。3. mysql里的大表用mycat做水平拆分,是不是要先手動分好,再配置mycat4. window下mysql中文亂碼怎么解決??5. sass - gem install compass 使用淘寶 Ruby 安裝失敗,出現 4046. python - (初學者)代碼運行不起來,求指導,謝謝!7. 為啥不用HBuilder?8. python - flask sqlalchemy signals 無法觸發9. python的文件讀寫問題?10. 為什么python中實例檢查推薦使用isinstance而不是type?
