Adding Vue directives to elements programmatically: a step-by-step guide to v-if
P粉883973481
P粉883973481 2023-09-07 13:54:54
0
1
565

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粉883973481
P粉883973481

reply all(1)
P粉764785924

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!