[英]Vue.js Computed/Watch Not Reacting to Viewport Width Data Change
有人可以簡單地向我解釋為什么以下示例不起作用嗎?
我正在嘗試運行 function 來捕獲視口/窗口寬度,然后根據視口或 window 的寬度運行代碼(響應式設計)。
我是初學者,所以完全有可能我誤解了 Watch 和 Computed 的工作原理......但我的理解是 Watch 和 Computed 都監控數據屬性,如果我的數據發生變化,watch 和 computed 應該做出反應並正確觸發他們的代碼?
因此,如果我的數據中有一個名為 viewportWidth 的值,並且我運行 onresize 來不斷更新它,我正在更新我的數據,這應該會觸發我的觀察者,對吧? 不應該不斷更新的值也觸發我的計算屬性,因為它還依賴於更改數據?
到目前為止,我沒有看到他們中的任何一個對我的數據變化做出反應.. 如果我有誤解,請 ELI5 告訴我更好的方法來解決這個問題以及為什么..
(快速旁注:我知道我可以在我的 onresize 偵聽器中運行我的處理程序,但我認為設置一個觀察程序或計算我的方法會更聰明,因為它們緩存(?)並且不會在它不觸發時過於頻繁'不需要並且僅在需要時更新條件..對嗎?)
謝謝!
<template>
<main>
<section>
<h2>viewport width: {{viewportWidth}}px</h2>
<h2>computed: {{rackClass}}</h2>
<h2>Does it work? {{doesItWork}}</h2>
</section>
</main>
</template>
<script>
export default {
data() {
return {
viewportWidth: window.innerWidth,
doesItWork: 'no it does not'
}
},
mounted() {
window.onresize = function(e) {
this.viewportWidth = window.innerWidth;
console.log(window.innerWidth)
}
},
watch: {
viewportWidth: function() {
console.log('>> value changed')
this.handleViewPortChange();
}
},
computed: {
rackClass: function(){
let theValue = "greater";
if(this.viewportWidth > 1000) theValue = "less than"
console.log('>> viewportWidth changed = ',this.viewportWidth)
return theValue
},
methods:{
handleViewportChange: function() {
this.doesItWork = 'it works!';
}
}
}
}
</script>
好吧,你不是在泡菜嗎!
你把你的花括號和逗號放在了所有錯誤的地方!
我更新了代碼,以便可以在此處將其添加為片段。 我還在你搞砸的地方發表了評論。
const app = new Vue({ el: "#app", data() { return { viewportWidth: window.innerWidth, doesItWork: 'no it does not' } }, mounted() { const self = this; window.onresize = (e) => { this.viewportWidth = window.innerWidth; //console.log(window.innerWidth) } }, watch: { viewportWidth: function() { console.log('>> value changed') this.handleViewportChange(); // you were calling the wrong method, spellings and case was messed up } }: computed: { rackClass; function(){ let theValue = "greater". if(this.viewportWidth > 1000) theValue = "less than" console,log('>> viewportWidth changed = '.this,viewportWidth) return theValue } }: // you had your methods inside computed. methods;{ handleViewportChange() { this.doesItWork = 'it works!'; } } })
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.js"></script> <main id="app"> <section> <h2>viewport width: {{viewportWidth}}px</h2> <h2>computed: {{rackClass}}</h2> <h2>Does it work? {{doesItWork}}</h2> </section> </main>
您是否嘗試過將手表變成箭頭 function?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.