简体   繁体   English

元素更改时 DOM 不更新 (VUE)

[英]DOM does not update when element changes (VUE)

for a vue/mvc project i am making a page divided into html sections.对于 vue/mvc 项目,我将页面分为 html 部分。 If the user clicks on a button a javascript function is called that changes the display properties of the sections so that only the clicked section is shown.如果用户单击一个按钮,则会调用 javascript function 来更改部分的显示属性,以便仅显示单击的部分。

When the dom is created, it calls the function and correctly shows one section.创建 dom 时,它调用 function 并正确显示一个部分。 However when the button is clicked, the function is called again, but the dom does not change.但是,当单击按钮时,再次调用 function,但 dom 没有改变。

Here is the code for the created function:这是创建的 function 的代码:

created: function () {
  var self = this;
  var sectionElements = document.getElementsByTagName("section");
  for (var i = 0; i < sectionElements.length; i++) {
    self.sections.push({ isSelected: false, object: sectionElements[i] });
  }
  for (var i = 0; i < self.sections.length; i++) {
    self.sections[i].isSelected = false;
  }
  this.showSelectedSection(0);   
},

Here is the code of the javascript function.这里是 javascript function 的代码。

 showSelectedSection(index) {
  for (var i = 0; i < this.sections.length; i++) {
   if (i == index) {
      this.sections[i].isSelected = true;
      this.sections[i].object.style.display = "block";
   }
   else {
      this.sections[i].isSelected = false;
      this.sections[i].object.style.display = "none";
   }
 }

Does anyone know why this is happening and how i can fix it?有谁知道为什么会发生这种情况以及我该如何解决? Any tips or help is greatly appreciated.非常感谢任何提示或帮助。

First of all, I don't totally get why you're using self = this in this example, seems like it's not necessary.首先,我不完全明白为什么你在这个例子中使用self = this ,似乎没有必要。 Nevertheless that is not your problem.尽管如此,这不是你的问题。 You're modifying an object inside an array, and you're doing this by accessing the index.您正在修改数组中的 object,并且您通过访问索引来执行此操作。 Normally that would be ok, but vue is not aware of this change.通常这会是好的,但 vue 不知道这个变化。 Try either passing the direct reference to the object inside the array or add a deep watch to your array so vue can hear this changes and make the proper modifications to your DOM.尝试将直接引用传递给数组内的 object 或向您的数组添加一个深度监视,以便 vue 可以听到这些更改并对您的 DOM 进行适当的修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM