0

I have a boolean JavaScript variable tied to a Vue instance. When I change that boolean, Vue doesn't see the change. But when I declare a boolean in Vue from the beginning, Vue does see the change. Why the difference?

In my example Vue doesn't see someBoolean changing. It does see vueBool changing. Clicking the button should flip both boolean variables.

JavaScript:

let someBoolean = true;

let vInstance = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!',
    vueBool: true,
    vSomeBoolean: someBoolean
  }
})

document.getElementById("btnBooleanToggle").addEventListener("click", function(){
    somBoolean = !someBoolean;
    vInstance.vueBool = !vInstance.vueBool;
})

HTML

<script src="https://unpkg.com/vue"></script>

<div id="app">
  <p>{{ message }}</p>
  <p>
  Boolean declared inside Vue: {{vueBool}}
  </p>
  <p>
  Boolean declared outside Vue: {{vSomeBoolean}}
  </p>

  <button id="btnBooleanToggle">
  Toggle booleans
  </button>
</div>

Link to jsfiddle

1 Answer 1

2

This is simply how Vue works. Vue creates accessor properties for the data inside the instance so that it knows when the data changes. Vue can't setup anything to track data from anything outside of its system.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm confused though because Vue seemingly has no problem seeing changes on objects declared outside Vue that are then tied to the Vue instance. But it just won't work with plain "non-object" booleans?
So, if its referenced from inside the Vue system, and its an object, Vue can attach a Proxy object to it to watch for changes. This is not possible with primitives like numbers and booleans.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.