简体   繁体   English

如何在不渲染的情况下获取 vue 组件的 DOM?

[英]How to get DOM of a vue component without rendering it?

Suppose I have a simple Vue component like this:假设我有一个像这样的简单 Vue 组件:

Vue.component('blog-post', {
  props: ['title'],
  template: '<h3>{{ title }}</h3>'
})

I don't want to render the component.我不想渲染组件。 I just want to pass the title somehow into blog-post component inside my script code, and get the DOM accordingly.我只是想以某种方式将title传递到我的脚本代码中blog-post组件中,并相应地获取 DOM。 For example, if I pass the title value Hello , then I expected the full DOM as <h3>Hello</h3> .例如,如果我传递了标题值Hello ,那么我期望完整的 DOM 为<h3>Hello</h3> I'll assign the DOM into a variable for using later.我会将 DOM 分配到一个变量中以供以后使用。

One solution is to create a new Vue instance with only the target component, $mount it, and then get the outerHTML of its $el (root element) :一种解决方案是创建一个仅包含目标组件的新 Vue 实例, $mount它,然后获取其$el (根元素)outerHTML

 <script src="https://unpkg.com/vue@2.6.12/dist/vue.min.js"></script> <script> Vue.component('blog-post', { props: ['title'], template: '<h3>{{ title }}</h3>' }) const app = new Vue({ template: `<blog-post title="Hello world" />` }).$mount() console.log(app.$el.outerHTML) </script>

If you want to get HTML of your component, you must to use ref attribute of parent element.如果要获取组件的 HTML,则必须使用父元素的ref属性。

Try something like that:尝试这样的事情:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  </head>
  <body>
    <div id="app">
      <div>
        <button @click="logComponentBlogPost">Log Component</button>
      </div>

      <div v-show="false" ref="BlogPost">
        <blog-post title="Hello Word"></blog-post>
      </div>
    </div>

    <script>
      let BlogPost = Vue.component('BlogPost', {
        props: ['title'],
        template: '<h3>{{ title }}</h3>',
      });

      new Vue({
        el: '#app',
        components: { BlogPost },
        methods: {
          logComponentBlogPost() {
            console.log(this.$refs.BlogPost.innerHTML);
          },
        },
      });
    </script>
  </body>
</html>

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

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