【问题标题】:Passing props to root instances in Vue.js在 Vue.js 中将 props 传递给根实例
【发布时间】:2025-12-07 18:40:01
【问题描述】:

问题

我正在尝试将道具传递给我的根构造函数。我明白propsDatais the way to go

var appComponent = Vue.component('app', require('./components/app/app.vue.html'));
new Vue({
    el: '#app-root',
    router: new VueRouter({ mode: 'history', routes: routes }),
    propsData: { test: 'hi!' },
    components: { appComponent },
    render: h => h('app')
}); 

这是接收道具的AppComponent

export default class AppComponent extends Vue {

    @Prop()
    test: string;

    mounted() {
        console.log('test = ' + this.test);
        // result: test = undefined
        // expected: test = 'hi!'
    }
}

我尝试过的事情

使其在开发中(不在生产​​中)工作的唯一方法是:

test: string;

beforeCreate() {
    this.test = this.$root.test;
}

它适用于开发(windows),但在部署(linux)中我收到了这个打字稿错误:

ERROR in [at-loader] ClientApp/components/app/app.ts:14:34
    TS2339: Property 'test' does not exist on type 'Vue'.

Here 是另一篇讨论这个的帖子。

【问题讨论】:

    标签: javascript typescript vue.js


    【解决方案1】:

    您可以在data 对象中传递props,这是createElement 别名h 函数接受render 选项的第二个参数

    render: h => h('app', { props: { test: 'hi!' }})
    

    【讨论】: