[Vuejs]-Vue reverse data binding

0👍

you can use a computed property or a watcher to do this:

https://v2.vuejs.org/v2/guide/computed.html

0👍

tldr; bind x to the Vue data object, but x itself has to be the member of an object.

In order for VueJS to update the input box, the bound variable needs to be reactive. Other answers that suggest watchers or computed variables would fail when a global variable is updated outside of VueJS if xis not reactive.

Vue can only make certain kinds of variables reactive. Notice in the following code that since x is an object that contains a member, when Vue instance is bound to that member, the member becomes “reactive.” However if we bind directly to a value, y it is not updated. (Codepen link https://codepen.io/bricksphd/pen/mdVrYyK)

var x = { value: "object" };
var y = "alone"

setInterval(update, 1000);

function update() {
    x.value = "" + Math.random();
    y.value = "" + Math.random();
}

const app = new Vue({
    el: '#app',
    data: {
        x: x,
        y:y
    }

});

Leave a comment