0

I'm looping an array of element and I'd want to recursively display that element with given template

and then inside that template use button with toggle to show/hide deeper level template of Childs of given element (Child is also an Element)

<div v-for="(element in elements)">
    <MyTemplate :element="element"></MyTemplate>
</div>

Here's my template:

<template>
    <div>element.Name</div>
    <button @click="toggleSomehow">
        // I'd want to display it under that button when he's "showing"
        <MyTemplate :element="element.Child"></MyTemplate>
    </button>
</template>

But I'm not really sure how to do that SHOW/HIDE button without binding it with some property or array, but I'd rather want to avoid it because everything has to be kind of dynamic

1 Answer 1

1

You should add toggleable data to your MyComponent component like visible See example below

Vue.component('my-template', {
  template: '#my-template',
  props: {
    element: {
      type: Object,
      required: true
    }
  },
  
  data() {
    return {
      visible: false
    }
  },

  methods: {
    toggleVisible() {
      this.visible = !this.visible
    }
  }
});

new Vue({
  el: '#app'
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<script type="text/x-template" id="my-template">
  <div>
    <div>{{element.name}}</div>
    <button @click="toggleVisible" v-if="element.child">toggle</button>
    <my-template v-if="visible" :element="element.child" />
  </div>
</script>

<div id="app">
  <my-template :element="{name: 'test', child: {name: 'child test'}}" />
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.