【问题标题】:Dynamically render injected vue components动态渲染注入的 vue 组件
【发布时间】:2022-08-15 02:59:22
【问题描述】:

我目前正在开发第三方应用程序,使用 Vue 渲染组件。

Vue 应用程序初始化和挂载后,第三方应用程序会动态加载组件。结果,我只能看到组件的 HTML,而实际上看不到要渲染的模板。意思是,当我检查时,我可以看到类似<my-component></my-component> 的内容,但看不到myComponent 的模板。

这是我提到的关于https://jsfiddle.net/EmeraldCodeNinja/31jkmzgc/12/ 的挑战示例。在这个例子中,你会找到一个按钮,点击它会使用 JavaScript 将 vue 组件附加到 DOM。

请提出一种方法来完成这项工作,这样我就可以渲染动态添加的组件。

注意:目的不是让 JSFiddle 工作,它只是模拟我面临的挑战的一个例子。我的目的是让动态添加的 vue-component 进行渲染。

从 JSFiddle 发布相同的 HTML 和 JS

HTML

<script src=\"https://unpkg.com/vue@3.2.37/dist/vue.global.js\"></script>
<div id=\"app\">
  <sample-button></sample-button>
  <div id=\"new-button-wrap\"></div>
</div>

<script id=\"sample-button\" type=\"text/html\">
    <button @click=\"addNew\">Add Another Sample Button</button>
</script>

JS

const app = Vue.createApp();

app.component(\'sample-button\', {
    template: \'#sample-button\',
  setup() {
    const addNew = function() {
      var div = document.createElement(\'div\');
      var sampleBtn = document.createElement(\'sample-button\');
      div.textContent = \'here a button should appear, but instead a tag is appearing\'
      div.appendChild(sampleBtn)
        document.querySelector(\'#new-button-wrap\').appendChild(div)
    }
    return {
        addNew
    }
  }
})

app.mount(\'#app\');
  • 您能否在问题中发布您有问题的代码而不是外部链接
  • 完成@JaromandaX
  • 这回答了你的问题了吗? Dynamically adding different components in Vue
  • 没有@Duannx。组件必须动态添加,Vue 不更新任何参数。在我的例子中,第三方脚本会更新组件的 HTML,将新组件注入到初始化的 Vue 应用程序中。
  • 在您的情况下,我认为您应该使用 custom elements 因为 Vue 无法理解来自 Vue 应用程序外部的 HTML。 See more

标签: javascript vue.js vue-component vuejs3


【解决方案1】:

您可以使用createAppmount 方法在运行时创建一个Vue 实例,将其附加到DOM。

createApp({
      template: "<button id=`button`>I'm a button!</button>",
}).mount(document.getElementById("button-container"));

Here 是 CodeSandbox 链接

【讨论】:

    猜你喜欢
    • 2021-03-19
    • 2021-02-08
    • 2019-05-31
    • 2021-09-12
    • 2021-09-15
    • 1970-01-01
    • 2020-05-22
    • 2020-01-19
    • 2019-10-20
    相关资源
    最近更新 更多