Kamil
Kamil

Reputation: 91

How to pass a reactive variable into Vue.js component?

I can't find out how to pass a reactive variable into Vue.js component without using HTML templates.

I use this code for component rendering

var App = require('./app.vue').default;
var test = 'hey!';

var app = new Vue({
    el: '#app',
    data: {
        message: test
    },
    components: { App },
    render: h => h('app', { props: {message: test}})
})

It works fine and my component renders with 'hey', but the problem that I am facing is the fact that whenever I change

var test = 'hey!';

variable (in browser's developer console) then nothing seems to change in my component, it's only rendering 'hey'.

As I understand, I would have to pass

app.message

into my component to make it reactive, but how would I go about doing this? Or perhaps is there some other way to achieve this?

I set it up to work with Typescript and single file components in Webpack.

Upvotes: 0

Views: 1466

Answers (1)

Kamil
Kamil

Reputation: 91

I was able to find a solution, for anyone with a similar problem - you have to change your render to a function, like this

var App = require('./app.vue').default;

var app = new Vue({
    el: '#app',
    data: {
        message: 'hey!'
    },
    components: { App },
    render (h) {
        return h('app', {
            props: {
                message: this.message
            }
        })
    }
})

you can add this below to test it in your browser's developer console

window['vue_test'] = app;

then in developer console you can just type in

vue_test.message = 'new value!'

and HTML Dom should be updated with changes. Only data properties are reactive and that's why it didn't work before with this variable:

var test = 'hey!';

Upvotes: 1

Related Questions