Rob*_*and 5 javascript vue.js vuejs2
在 Vue.js 中,我有一个var app = new Vue({...});组件Vue.component('mycomponent', ...,我可以通过直接添加到 html 中来使用此类组件,没有任何问题<mycomponent></mycomponent>。我想做的是在单击按钮后或发生其他此类事件时按需动态添加这些组件。在原始 JS 中,我会document.createElement...在事件触发时使用,然后将el.appendChild..其添加到 html 中。我如何对 Vue.js 做同样的事情?
我没有用 Node.js 做任何花哨的事情。这是在单个 html 页面上,扩展<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>名为<head>.
为此,“Vue 方式”通常涉及使用v-if、v-for或<component>,具体取决于您想要执行的操作:
v-if根据条件有条件地显示组件/元素。v-for呈现组件/元素的列表。<component>渲染动态组件/元素。因此,为了实现您在问题中所描述的内容,您可以声明一个布尔数据属性,visible如下所示:
data() {
return {
visible: false
}
}
Run Code Online (Sandbox Code Playgroud)
并使用它来v-if控制模板中组件的可见性:
<mycomponent v-if="visible"></mycomponent>
Run Code Online (Sandbox Code Playgroud)
这需要<mycomponent>预先存在于模板中。如果您不知道要显示哪种组件,那么您可以在模板中包含每种可能性并根据某种条件显示您想要的组件:
<comp1 v-if="comp1Visible"></comp1>
<comp2 v-if="comp2Visible"></comp2>
<comp3 v-if="comp3Visible"></comp3>
Run Code Online (Sandbox Code Playgroud)
<component>或者您可以与另一个数据属性 ( ) 一起使用comp,您可以将其设置为要显示的组件的名称:
<component v-if="visible" :is="comp"></component>
Run Code Online (Sandbox Code Playgroud)
你所描述的(document.createElement后面跟着el.appendChild)在Vue中不存在。Vue 有一个严格的渲染机制,你需要使用它;不可能动态实例化组件并将它们随机粘贴到 DOM 中。从技术上讲,您可以comp = new Vue()等效于document.createElementand then el.appendChild(comp.$el),但这可能不是您想要做的,因为您将创建一个独立的 Vue 实例,您必须手动管理该实例,并且没有简单的方法来传递数据。
| 归档时间: |
|
| 查看次数: |
9847 次 |
| 最近记录: |