扫码关注官方订阅号
如何做到点击一个按钮动态添加一个组件呢?是.vue组件
业精于勤,荒于嬉;行成于思,毁于随。
我是写在父组件中的:
Vue.component('mycontent', { props: ['content'], data() { return { coms: [], } }, render: function(h) { this.coms = []; for(var i = 0; i < this.content.length; i++) { this.coms.push(h(this.content[i], {})) } return h('p', {}, this.coms) }, });
调用的时候
<mycontent v-bind:content="content"></mycontent>
那么父组件中的content变化时,就会动态加载组件了
<template> <input type="text" v-model='componentName'> <button @click='add'>click me to add a component</button> </template> <script> // 引入要添加的所有组件 import component1 from './components/component1.vue' import component2 from './components/component2.vue' export default { data: function() { return { allComponents: [], componentName: '' } }, components: { // 注册所有组件 component1, component2 } methods: { add: function() { this.allComponents.push(this.componentName) // 重置输入框 this.componentName = '' }, render: function(h) { // h 为 createElement 函数,接受三个参数 // tag // data // children 具体看文档吧 return h('p',this.allComponents.map(function(componentName) { return h(componentName) })) } } } </script>
更改data遍历data动态渲染component 就好了 ~~
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
我是写在父组件中的:
调用的时候
那么父组件中的content变化时,就会动态加载组件了
更改data
遍历data动态渲染component 就好了 ~~