How to clone vue element with functions in nuxt?

Viewed 637

I have the template like this

<template>
<div>
  <div id="hiddenElement">
    <MyElement v-for='...' @click="...">
    </MyElement>
  </div>

  <div id="appendElementsHere" />
</div<
</template>

The user can append the element into the list, so I have some function like this:

someFunc(){
const hidden = document.querySelector('#hiddenElement')
const target = document.querySelector('#appendElementsHere')
target.innerHtml += hidden.outerHtml
}

The element is cloned can append to the #appendElementsHere successfully, but the click function is not working. I think that maybe the click function in the vue element, not the html. How can I clone the element as vue-element, not html only? Or any idea to create vue element in the script (method) and then append to the dom ??

1 Answers

What you're doing is technically correct from a javascript perspective, however the click function doesn't work because you're not doing any data bindings after you "clone" the elements. I say "clone", because what you're doing is just passing a bunch of strings containing HTML. With that said, what you will have to do next is to add the event listeners to the cloned elements manually as well.

However, you could try to do it in a more Vue way, so instead of having a hidden component waiting to be cloned, you could create the Vue instance of the component you want (MyElement in your case) with code passing all the props/data you want and then append it to the element where you need it.

Here's an example with how to do it with buttons. If click on "Click to insert" you'll see how a CustomButton component gets appended to the right of the button.

Thanks,

Related