簡體   English   中英

如何在不渲染的情況下獲取 vue 組件的 DOM?

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

假設我有一個像這樣的簡單 Vue 組件:

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

我不想渲染組件。 我只是想以某種方式將title傳遞到我的腳本代碼中blog-post組件中,並相應地獲取 DOM。 例如,如果我傳遞了標題值Hello ,那么我期望完整的 DOM 為<h3>Hello</h3> 我會將 DOM 分配到一個變量中以供以后使用。

一種解決方案是創建一個僅包含目標組件的新 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>

如果要獲取組件的 HTML,則必須使用父元素的ref屬性。

嘗試這樣的事情:

<!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