IeuanG
IeuanG

Reputation: 504

Why does v-if not get affected when the data is updated later?

If I were to create an element such as that below:

<div id="helloWorldDiv" v-if="visible">
    Hello World
</div>

and then create a Vue instance for it:

var helloWorld = new Vue({
  el: "#helloWorldDiv",
  data: {
    visible: false
  }
});

I would expect that the line 'helloWorld.visible = true;' would show the element, but it has not effect. Can anyone explain why this doesn't work?

JSFiddle

Upvotes: 1

Views: 4795

Answers (2)

Mani Jagadeesan
Mani Jagadeesan

Reputation: 24265

I think you are getting started with Vue.js, which is great!

There are several changes you need to do in your sample app. Check this fiddle: https://jsfiddle.net/mani04/f20Ld806/

As you can see in that example, your show() function needs to be defined inside the methods of your Vue app. Also the show button needs be part of the app template, not outside of it.

You can find a lot more in Vue docs and tutorials online.

Upvotes: 2

PatrickSteele
PatrickSteele

Reputation: 14677

First off, I would suggest not manipulating the Vue instance from the outside. It'll make it harder to maintain the app as it grows.

However, as to your question, there's a number of issues with your JSFiddle:

  • You never set visible to true.
  • In your show function, you misspelled helloWorld as helloWolrd.
  • The show function and helloWorld variable need to be attached to the window so they can be globally accessed from the onclick event.

So if you update your javascript to:

var helloWorld = new Vue({
  el: "#helloWorldDiv",
  data: {
    visible: false
  }
});


function show() {
  helloWorld.visible = true;
};

window.helloWorld = helloWorld;
window.show = show;

Your code works as expected.

Upvotes: 1

Related Questions