0

I Want to add new element to the DOM after new Vue instance created. I know I can re initiate the instance of vue but it seems it is not good idea because vue have to re render all elements again. So is there a method to bind just new element to the data scope?

<body>
  <div id="app">
    <span>{{ a }}<span>

    <div id="newElem"></div>
  </div>
</body>

<script>

    $(document).ready(function () {
        var mainApp = new Vue({
            el: "#app",
            data: {
                "a": "aa",
                "b": "bb"    
            }
        });

        $("#newElem").html("<span>{{ b }}</span>")

    });

</script>

This code renders {{ b }} unbinded. I am looking for a method for preventing this.

Thanks

Mohsen Mirshahreza
  • 155
  • 1
  • 1
  • 10

2 Answers2

0

Have you tried something like this?

<div v-html="newElem"></div>

el: "#app", data: { "a": "aa", "b": "bb"
}, created() { this.newElem = "<span>{{ b }}</span>"; }

Sergey Bogdanov
  • 631
  • 1
  • 4
  • 11
0

It's really hard to tell your ultimate goal here but I'll take a shot.

Ideally, you wouldn't touch the DOM, you'd want to update the data and let Vue handle the DOM for you.

I think you want to initialize b as undefined and set that when you're ready for it to be displayed.

data: {
  a: 'aa',
  b: undefined,
}

Then in your template you can have something like this:

<span v-if="b">{{ b }}</span>

This way the span won't display until b is truthy.

Then, later, when b is ready, you would mainApp.b = 'bb'.

Here's a quick demo: http://jsfiddle.net/crswll/vtu8nzea/1/

If you make add a more complete use case I can likely help further.

Also, this answer might help as well. It's kind of like the next level of this thinking: Vuejs: v-model array in multiple input

Bill Criswell
  • 32,161
  • 7
  • 75
  • 66
  • My problem is not with data. it is about dynamic DOM. I am developing a software that have a run time designer so i have to handle run time elements that binds to current data. – Mohsen Mirshahreza Dec 12 '18 at 12:39
  • Thanks for the answer, but my case is the situation that element is not present at first and it will add to the document dynamically. a jsfiddle shows you the exact condition : https://jsfiddle.net/mirshahreza/y3hb790a/5/ – Mohsen Mirshahreza Jan 06 '19 at 13:45