search

Home  >  Q&A  >  body text

Adding Vue directives to elements programmatically: a step-by-step guide to v-if

We can add custom attributes to elements programmatically using pure JS, like element.attr('data-attr', someValue), but like v-if What about the Vue directive

Given the following elements

<p v-html="data.title"></p>

How to add v-if programmatically? I'm asking this for automation purposes as there will be hundreds of dynamic variables that may or may not exist.

The expected result is

<p v-if="data.title" v-html="data.title"></p>

The only step I know of is to use ref to get the element in created().

P粉883973481P粉883973481462 days ago618

reply all(1)I'll reply

  • P粉764785924

    P粉7647859242023-09-08 12:52:54

    According to the declaration - There will be hundreds of dynamic variables that may or may not exist. But if I see in your comment, you said >No loops. So how do you render dynamic elements?

    From my understanding, you want to dynamically bind the data attributes into the HTML template. You can give this solution a try and see if it meets your requirements.

    new Vue({
      el: '#app',
      data: {
        data: {
            heading: '<H1>Heading 1</H1>',
          title: '<h3>Title 1</H3>'
        }
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    
    <div id="app">
      <p v-for="(item, index) in Object.keys(data)" :key="index"  v-html="data[item]"></p>
    </div>

    The code snippet above always works with existing dynamic properties.

    reply
    0
  • Cancelreply