简体   繁体   中英

Tracking data changes in Vue.js on a Javascript that already exists?

I have a project that I've been working on for awhile that I might want to use vuejs for some of the UI elements. I fired up a tutorial and tried to piece together a basic example.

I have a basic javascript object like so:

var hex = {};
hex.turn_phase = 'unit_placement';

On my template, I have:

var app = new Vue({
        el: '#vue-test',
        data: {
            message: 'Hello Vue!',
            turn_phase: hex.turn_phase,
        },
        delimiters: ["<%","%>"],
        mounted: function() {
            this.fetch_turn_phase();
        },
        methods: {
            fetch_turn_phase: function() {
                Vue.set(this, 'turn_phase', hex.turn_phase);
            },
        }
    });

This renders the correct turn_phase on the template initially, but if I change the hex.turn_phase in the browser console, the template doesn't react.

Is there something that I missed in this basic example?

Vue creates all the data variables, computed properties and values returned from methods reactive. in your case since you are changing hex , which is not a vue variable, so vue will not detect any changes in this variable. However if you change message variable, it will be reflective and will be changed in the template.

It looks like you may have made things unnecessarily difficult. Just access your Vue instance via app ?

Always make sure you go through the setters generated by Vue.js. These are watched and will re-render your component.

在此处输入图像描述

Instead, try using

app.turn_phase = 'unit_placement';

You can get a better understanding here, Reactivity

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM