简体   繁体   English

如何将反应变量传递到Vue.js组件中?

[英]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. 我不知道如何在不使用HTML模板的情况下将反应变量传递到Vue.js组件中。

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. 我将其设置为与Typescript和Webpack中的单个文件组件一起使用。

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. 和HTML Dom应该进行更改进行更新。 Only data properties are reactive and that's why it didn't work before with this variable: 仅数据属性是反应性的,这就是为什么此变量之前无法使用的原因:

var test = 'hey!';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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