0

I can't get how to use v-html to save an existing content. For example:

<div ref="content" v-html="content">Hello, World! A lot of divs</div>

How to make to div content was replace only when I will assign a some not null value with content? Or how to make it in another way? Or is the single way to request div content asynchronously?

The next way works, of course, but I lose a data binding.

this.$refs['content'].innerHTML = "New content";

P.S. I am migrating from jQuery and still can't think in Vue.js philosophy clearly.

Denis Sologub
  • 7,277
  • 11
  • 56
  • 123

2 Answers2

1

Actualy, you must read vue documentation.
In your component you must declare content in data, and simply change it in oher places, i.e. in button's click handler or inside component's methods:

new Vue({
  el: "#root",
  data: function () {
     return { 
       content: 'Hello, World! A <b>lot</b> of divs'
     };
  },
  methods: {
     changeText: function() {            
        this.content = 'This text from component';
     }
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<div id="root"> 
    <div v-html="content"></div>        
    <button v-on:click="content = 'This text from button'">Click me</button>
    <button v-on:click="changeText">And me</button>
</div>
tony19
  • 125,647
  • 18
  • 229
  • 307
Alex
  • 1,373
  • 8
  • 15
  • 1
    your data should be a method that returns an object when called, otherwise all instances of the component will share the same object and I don't think this is what you want. – Radu Diță Mar 17 '19 at 13:12
  • you should not use fat arrow functions when declaring data objects. Vue won't be able to bind this to it and you may run into some issues. See this SO thread for details https://stackoverflow.com/questions/48980865/vue-js-difference-of-data-return-vs-data – Radu Diță Mar 17 '19 at 13:26
  • Thank you, seems I get so I will download it asynchronously still, `v-if` looks simple but it will keep initial content in the memory as I got. – Denis Sologub Mar 17 '19 at 13:29
1

You could assign a default value to content.

data () {
  return {
    content: 'Hello, World! A lot of divs'
  }
}

When you'll assign a new value to content it will get rendered.

Another way would be to check if content is not null and have 2 different divs using v-if/v-else for conditional rendering.

<div v-if="content" v-html="content"></div>
<div v-else>Hello, World! A lot of divs</div>

and the script

export default {
  name: 'customComponent',
  data () {
     return {
       content: null
     }
  }
}
Radu Diță
  • 13,476
  • 2
  • 30
  • 34