【问题标题】:Can't pass data from main.js to App.vue in Vue js?无法在 Vue js 中将数据从 main.js 传递到 App.vue?
【发布时间】:2021-09-02 12:51:23
【问题描述】:

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

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 未定义时给出错误。传递硬编码值有效。在渲染线上不使用 props 没有错误,但 App 不接收数据。是我做错了吗?

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

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

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

    你可以阅读箭头函数与常规函数here

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2019-03-08
        • 1970-01-01
        • 2021-08-07
        • 1970-01-01
        • 2020-03-17
        • 2020-09-26
        • 2017-07-27
        • 2015-01-03
        • 2019-03-22
        相关资源
        最近更新 更多