javascript - 创建动态组件 VUE
问题描述
我对如何创建动态组件有疑问,而不是通过 label <component :is=''>
,如果不是,则该组件在 DOM 中不存在,并通过 javascript 插入它。
如在 jquery 添加一个$("body").append("<div class="modal"></div>")
, 添加一个新的模态
示例:https ://jsfiddle.net/yu9oca2n/
代码:https ://codesandbox.io/embed/vue-template-5cx5l?fontsize=14
jQuery
代码示例 JQuery
$("#button").click(function() {
$("#modals").append("<div class='modal'>modal</div>");
});
<!doctype html>
<html>
<head></head>
<body>
<div id="modals"></div>
<hr>
<button id="button">add input tag</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>
VUE
组件父级
<template>
<div>
<p>Hello</p>
<hr>
<a @click="insertModal">Insert Modal</a>
<hr>
<modal num="1"></modal>
</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {},
methods: {
insertModal() {
/**
* How to do so that when you enter here,
* add one more modal, without putting this in a list,
* because this modal can be called from anywhere on the web
*
* MODAL : <modal num="_x_" @clickEvent="eventClick"></modal>
*/
// ??
}
},
eventClick() {
/** modal event click */
}
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
组件模态
<template>
<div>MODAL {{num}}</div>
</template>
<script>
export default {
name: "modal",
props: ["num"],
data: function() {
return {};
},
methods: {}
};
</script>
解决方案
在组件数据中创建一个数组,并为数组中的每个项目显示一个模式
<template>
<div>
<p>Hello</p>
<hr>
<a @click="insertModal">Insert Modal</a>
<hr>
<modal v-for="num in modals" :num="num" :key="num" @clickEvent="eventClick($event, num)"></modal>
<modal num="1"></modal>
</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {},
data() {
return {
modals: [],
};
},
methods: {
insertModal() {
this.modals.push(this.modals.length)
}
},
eventClick($event, modalNumber) {
/** modal event click */
}
};
</script>
推荐阅读
- c# - c#如何在一个循环中运行两个foreach循环
- windows - 在 windows 中限制用户的 CPU 使用率
- c - 关于打印顺序图案的问题
- vba - VBA,取消选择列表框中首先强制选择的项目
- c++ - c++ 库的公共头文件中应该包含哪些内容?
- c# - C# Windows 窗体,如何使用 webbrowser 设置默认下载位置?
- transactions - BigQuery/以太坊数据集 - 如何编写代码
- javascript - 错误:解析 url 时出错:将数据库迁移到 heroku 时未定义
- sapui5 - 路由器或目标“sap.f.routing.Router”的指定类未定义
- r - R:简单代数和的近似误差