zoukankan      html  css  js  c++  java
  • vue2.0动态添加组件

    方法一、
    <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('div',this.allComponents.map(function(componentName) { return h(componentName) })) } } } </script>
    方法二、

    html

      <div id="app">
        <button @click="add('a-component', 'test')">Add A</button>
        <button @click="add('b-component', 'test')">Add B</button>
        <ul>
          <li :is="item.component" :text="item.text" v-for="item in items"></li>
        </ul>
      </div>

    javascript

    var AComponent = Vue.extend({
      props: ['text'],
      template: '<li>A Component: {{ text }}</li>'
    })
    
    var BComponent = Vue.extend({
      props: ['text'],
      template: '<li>B Component: {{ text }}</li>'
    })
    
    
    new Vue({
      el: '#app',
      components: {
        'a-component': AComponent,
        'b-component': BComponent,
      },
      data: {
        items: []
      },
      methods: {
        add(component, text) {
          this.items.push({
            'component': component,
            'text': text,
          })
        }
      }
    })

    方法三、

    我是写在父组件中的:

    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('div', {},
                    this.coms)
            },
        });

    调用的时候

    
        <mycontent v-bind:content="content"></mycontent>
    

    那么父组件中的content变化时,就会动态加载组件了

     
  • 相关阅读:
    STL
    Python
    Swift学习笔记
    Swift学习笔记
    Cocos2d-x -- 如何让背景从上到下滚动
    Cocos2d-x -- 图片菜单按钮
    How to change in the Cocos2d-x project from landscape to portrait both in iOS and Android
    系统集成项目管理工程师和信息系统管理工程师的区别是什么?
    公积金取出来后悔了 公积金取出来好还是不取好?
    青岛公积金贷款额度最高多少?怎么算?
  • 原文地址:https://www.cnblogs.com/h2zZhou/p/8036953.html
Copyright © 2011-2022 走看看