【问题标题】:How to access DOM in Vue.js如何在 Vue.js 中访问 DOM
【发布时间】:2020-09-08 13:23:27
【问题描述】:

我正在尝试使用 Vue.js 访问 DOM。我正在mounted() 生命周期内编写代码,但没有得到任何结果。

代码使用 vanilla JavaScript 可以完美运行。

我正在使用 v-html 指令在 span 标签内插入 html。

    <span class="email" v-html="text"></span>

然后在挂载的生命周期中

  mounted() {
    let images = document.getElementsByClassName(
      "mcnImageCardBottomImageContent"
    );
    console.log(images);
    // It is returning an empty array
 
  },

如何在 Vue.js 中访问 DOM?

【问题讨论】:

    标签: javascript vue.js dom vuejs2 vue-directives


    【解决方案1】:

    您需要知道,您在 Vue.js 或 react 中看到的 HTML 标记并不是真正的 HTML 标记。它被解析为纯 javascript 对象、虚拟 DOM。

    你需要等到 vuejs 渲染它的虚拟 DOM。你可以用this.$nextTick()来做到这一点

    mounted() {
       this.$nextTick(() => {
          let images = document.getElementsByClassName(
            "mcnImageCardBottomImageContent"
          );
          console.log(images);
            // It is returning an empty array
          })
    }
    

    【讨论】:

      【解决方案2】:

      这样的东西会起作用吗? :)

        mounted() {
          document.onreadystatechange = () => {
            if (document.readyState === "complete") {
              console.log("Page loaded");
              // Do stuff here
            }
          };
        }
      

      【讨论】:

      • 我在其他类似问题中看到过这个答案,但是,由于某种原因,这个箭头函数永远不会触发。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-19
      • 2012-12-29
      • 2016-02-05
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 2017-05-05
      相关资源
      最近更新 更多