2016-02-25 30 views
2

我使用Enquire.jsVue.js來查詢瀏覽器的大小並相應地更新兩個數據屬性。所以,如果我這樣做:使用Enquire.js和Vue.js查詢瀏覽器的大小

ready: function() { 
    // Listen for changes in the browser's size 
    window.addEventListener("resize", 
    enquire.register("screen and (max-width:400px)", { 
     match: function() { 
      this.displayIsLarge = false; 
      this.displayIsSmall = true; 
      console.log("the screen is now small"); 
     }, 
     unmatch: function() { 
      this.displayIsLarge = true; 
      this.displayIsSmall = false; 
      console.log("the screen is now large"); 
     } 
    }) 
    ); 
} 

它將輸出在控制檯中正確的消息(的jsfiddle here),但它沒有改變displayIsLargedisplayIsSmall值。我在這裏錯過了什麼?

回答

2

問題出在this的範圍內。完整的工作代碼爲:

ready: function() { 
    var self = this; 
    // Listen for changes in the browser's size 
    window.addEventListener("resize", 
    enquire.register("screen and (max-width:400px)", { 
     match: function() { 
      self.displayIsSmall = true; 
      self.displayIsLarge = false; 
      console.log("the screen is now small"); 
     }, 
     unmatch: function() { 
      self.displayIsLarge = true; 
      self.displayIsSmall = false; 
      console.log("the screen is now large"); 
     } 
    }) 
    ); 
} 

的jsfiddle here