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. javascript - vue-router怎么不能實現跳轉呢2. npm鏡像站全新上線3. 老哥們求助啊4. css3 - 請問一下在移動端CSS布局布局中通常需要用到哪些元素,屬性?5. mySql排序,序號6. html5 - angularjs中外部模版加載無法使用7. django - 后臺返回的json數據經過Base64加密,獲取時用python如何解密~!8. node.js - node 客戶端socket一直報錯Error: read ECONNRESET,用php的socket沒問題哈。。9. tp6表單令牌10. 我的html頁面一提交,網頁便顯示出了我的php代碼,求問是什么原因?
