无法在 Vue js 中将数据从 main.js 传递到 App.vue?



在我的main.js中,我进行身份验证,然后填充一个数据属性。我正试图将该数据属性传递给应用程序组件,但似乎不可能?

main.js

import Vue from 'vue'
import App from './App.vue'
new Vue({
data: {
test: 'test'
},
//render: h => h(App)
render: h => h(App, { props: { 'test': this.test }})
}).$mount('#app')

App.vue

<template>
<div id="app" :test="test">
<h1>{{test}}</h1>
</div>
</template>
<script>
export default {
name: 'app',
props: ['test']
}
</script>

只是将错误作为test和/或this.test未定义。传递硬编码的值是有效的。在渲染线上不使用道具没有错误,但应用程序不会接收数据。我只是做错了吗?

您可以将render设置为正常函数,以便this引用Vue实例:

render: function (h) {
return h(App, { props: { test: this.test } });
}

您的问题是将render定义为匿名箭头函数。这意味着它的this上下文没有绑定到Vue实例。如果您希望函数的上下文是";托管";对象,则必须使用function语法来定义它。

new Vue({
data: {
test: 'test'
},
render(h) {
return h(App, { props: { 'test': this.test }})
}
}).$mount('#app')

你可以在这里阅读箭头函数与常规函数

最新更新