Why is Vue breaking my own code dom modifications?

问题: So I've got a class of mine, it's quite big so I cannot include it here, but essentially: var MyClass = function(options) { this.options = {} this.options = $.extend(...

问题:

So I've got a class of mine, it's quite big so I cannot include it here, but essentially:

var MyClass = function(options) {
  this.options = {}
  this.options = $.extend(true,this.options,options);
  this.init();
}

MyClass.prototype = {
  init:function(){
    this.set_events();
  },

  set_events:function(){
    // attach some dom events that in turn alter the dom (change some data- properties)
  }
}

What is quite curious to me, is that IF I instantiate it after Vue, MyClass will work properly and it will be able to modify the dom as well will work.

var vueapp = new Vue({
  // init stuff
});

myclassinstance = new MyClass(); // OK

But, if I'll do the opposite:

myclassinstance = new MyClass(); // WILL NOT WORK (it won't be able to change data- properties upon dom events)

var vueapp = new Vue({
  // init stuff
});

Note #1: I've got no errors in console.

Note #2: Dom events get executed: I'm able to log from them and inspect dom elements, but it seems I cannot change their props!

So what? Anyone can explain me why this happens?


回答1:

Even though the DOM looks exactly the same after Vue initialization, Vue has actually removed the original DOM and replace it with new DOM with some Vue's settings/properties.

If you add the event listeners before Vue init, the DOM with event listener would be replaced with new DOM without event listener. That's why.

e.g. https://codepen.io/jacobgoh101/pen/LrvXyb

var appElem = document.getElementById("app");
console.log('before Vue init', appElem === document.getElementById("app"));
// true

new Vue({
  el: "#app",
  data: {
    message: "Hello world"
  }
});

console.log('after Vue init', appElem === document.getElementById("app"));
// false

Btw, modifying the DOM outside of Vue is always considered bad practice.

Vue is a jealous library in the sense that you must let it completely own the patch of DOM that you give it (defined by what you pass to el). If jQuery makes a change to an element that Vue is managing, say, adds a class to something, Vue won’t be aware of the change and is going to go right ahead and overwrite it in the next update cycle. https://vuejsdevelopers.com/2017/05/20/vue-js-safely-jquery-plugin/

(jQuery or not, this is why modifying the DOM is bad)

  • 发表于 2018-07-05 15:31
  • 阅读 ( 248 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除