鍍金池/ 問答/Python  HTML/ 為什么vue中無法這樣對(duì)新老變量做比較

為什么vue中無法這樣對(duì)新老變量做比較

圖片描述

圖片描述

在一個(gè)interval定時(shí)器里面執(zhí)行一個(gè)getAll方法,這個(gè)getAll方法會(huì)使用axios循環(huán)讀取某個(gè)接口,一旦那個(gè)接口數(shù)據(jù)有變動(dòng),就會(huì)將新數(shù)據(jù)寫入vue.count中,我現(xiàn)在想實(shí)現(xiàn)的是一旦檢測(cè)到這個(gè)vue.count有變化就alert彈框并且audio標(biāo)簽播放聲音,但是我發(fā)現(xiàn)這樣做并沒有效果,原因是什么呢?為什么old和new始終是一樣的?

回答
編輯回答
情皺

watch你值得擁有

2017年4月22日 08:37
編輯回答
小眼睛

你可以參照這樣的寫法

    new Vue({
        el: "#app",
        data() {
            return {
                count: ''
            }
        },
        methods: {
            getAll() {
                return new Promise((resolve, reject) => {
                    axios.get('../json/menu.json').then(res => {
                        resolve(res.data)
                    })
                })
            }
        },
        watch: {
            count: function () {
                alert('數(shù)據(jù)發(fā)生變化')
            }
        },
        mounted() {
            let that = this;
            setInterval(async () => {
                that.count = await that.getAll()
            }, 5000);
        }
    })

使用watch來監(jiān)聽count

2017年9月19日 23:12
編輯回答
賤人曾

因?yàn)槟鉽ue.old=vue.count這兩個(gè)始終相等,你后續(xù)又用他們做比較,這種場(chǎng)景你可以使用watch實(shí)現(xiàn),或者
先不賦值

if(vue.count===vue.old){
    數(shù)據(jù)無變化
}else{
    alert('new message')
}
2017年11月20日 10:57