0

I would like to transform the span into a real element. When I try this way the appendChild gives me an error because the variable is a string and not and object. Any ideas?

export default{
    data(){
       ....
    }   
    methods:{
      update_period: function(event){
        var start = moment(event.start).format('M/D/Y'),
            end = moment(event.end).format('M/D/Y');
        
        var span = `<span @click="remove">{{ start }} - {{ end }}</span>`

        this.$refs.spans.appendChild(span);
      },
      remove: function(event){
        event.target.remove()
      }
    }
  }
<div ref="spans">

</div>

3
  • It's not 'dynamic HTML'. It's Vue template. In order to maintain reactivity, you'll likely need to compile the template and render nested Vue instance. Is there a reason why you're trying to do this with @click and not raw addEventListener? Commented Feb 20, 2020 at 17:03
  • I can use addEventListener without a problem, but there's a way to create the HTML element em 'realtime' and append to the div? Commented Feb 20, 2020 at 17:16
  • Not in any reasonable and conventional way, no. As for your case, <span v-for> all the way, as it's suggested below. Commented Feb 20, 2020 at 17:38

1 Answer 1

1

You can get the same result in this way:

<template>
    <div>
        <span @click="remove" v-if="period">{{ period }}</span>
    </div>
</template>
<script>
export default {

    data() {
        return {
            period: null,
        }
    },

    methods:{
        update_period(event) {
            this.period = moment(event.start).format('M/D/Y') + ' - ' + moment(event.end).format('M/D/Y')
        },
        remove() {
            this.period = null;
        }
    }

}
</script>
Sign up to request clarification or add additional context in comments.

3 Comments

Yeah, but I have a lot o "periods". I'm trying to solve in a way that I don't create a lot of v-ifs and variables to control them.
However, for sure there is a better way with Vuejs to achieve what you need. Using appendChild in a Vue component is not recommended. Maybe an array of object with each period and a v-for?
Indeed! It's a better way to use v-for with an array. Thanks.

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.