官术网_书友最值得收藏!

Watchers

So, how can we add/remove classes from thebodyif it's out of Vue's dominion? We'll have to do it the old-fashioned way with the browser's Web API. We need to run the following statements when the modal is opened or closed:

// Modal opens
document.body.classList.add('modal-open');

// Modal closes
document.body.classList.remove('modal-closed');

As discussed, Vue adds reactive getters and setters to each data property so that when data changes it knows to update the DOM appropriately. Vue also allows you to write custom logic that hooks into reactive data changes via a feature calledwatchers.

To add a watcher, first add thewatchproperty to your Vue instance. Assign an object to this where each property has the name of a declared data property, and each value is a function. The function has two arguments: the old value and new value.

Whenever a data property changes, Vue will trigger any declared watcher methods:

var app = new Vue({
  el: '#app'
  data: {
    message: 'Hello world'
  },
  watch: {
    message: function(newVal, oldVal) {
      console.log(oldVal, ', ', newVal);
    }
  }
});

setTimeout(function() {
  app.message = 'Goodbye world';
  // Output: "Hello world, Goodbye world";
}, 2000);

Vue can't update thebodytag for us, but it can trigger custom logic that will. Let's use a watcher to update thebodytag when our modal is opened and closed.

app.js:

var app = new Vue({
  data: { ... },
  watch: {
    modalOpen: function() {
      var className = 'modal-open';
      if (this.modalOpen) {
        document.body.classList.add(className);
      } else {
        document.body.classList.remove(className);
      }
    }
  }
});

Now when you try to scroll the page you'll see it won't budge!

主站蜘蛛池模板: 汉阴县| 乃东县| 铁岭县| 偏关县| 双流县| 三江| 方城县| 乌什县| 龙游县| 荣昌县| 永和县| 巢湖市| 达孜县| 尼勒克县| 连云港市| 古田县| 鱼台县| 年辖:市辖区| 陈巴尔虎旗| 岑巩县| 沧源| 五原县| 铁岭市| 腾冲县| 丹寨县| 黄浦区| 盐亭县| 陵川县| 谢通门县| 新津县| 高平市| 安义县| 黔东| 孝昌县| 台北市| 龙岩市| 陈巴尔虎旗| 金川县| 鞍山市| 沂源县| 金沙县|