Home > other >  problematically generated tree of components in vue2
problematically generated tree of components in vue2

Time:10-22

I have a scenario which i need to build a nested menu and the menu can have an infinite level of nested layers (even thought this will not happen) and I'm wanting to know what is the best way of building the list of child components dynamically?

This is some test code that I put together to try some dynamic code from a function that would essentially give me the list of components in an array etc. What is the best way of problematically building up the child components tree?

<template>
  <a-row>
    <div v-html="getContent()"></div>
  </a-row>
</template>
    
<script>
export default {
  methods: {
    getContent() {
      return `<div @click="sayHello()">RYAN</div>`
    },
    sayHello() {
      console.log('Hello there');
    }
  }
}
</script> 

CodePudding user response:

You can try with :is and pass component:

new Vue({
  el: '#demo',
  data() {
    return {
      component: '',
      contents: ['RYAN', 'DJURO', 'SPIRO']
    }
  },
  methods: {
    getContent() {
      this.component = 'comp'
    },
    
  }
})
Vue.component('comp', {
  template: `<div @click="sayHello">{{ content }}</div>`,
  props: ['content'],
  methods: {
    sayHello() {
      console.log('Hello there '   this.content);
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <button @click="getContent">getContent</button>
  <ul v-if="component">
    <li v-for="(cont, i) in contents" :key="i">
      <component :is="component" :content="cont"> </component>
    </li>
  </ul>
</div>

  • Related