【问题标题】:Vue 2, Cannot reference Prop Object in templateVue 2,无法在模板中引用道具对象
【发布时间】:2017-06-11 16:40:45
【问题描述】:

问题:尽管在 Vue DevTools 中我正确地传递了 prop,并且 router-view 组件可以访问它需要的正确格式的数据,但每当我尝试从模板中访问任何数据属性时我得到Uncaught TypeError: Cannot read property 'name' of null。这真的很令人困惑,因为从 DevTools 来看,一切都是有效的对象,并且属性不为空。

App.js

const game = new Vue({
    el: '#game',

    data: function() {
        return {
            meta: null,
            empire: null,
            planets: null
        };
    },

    created: () => {
        axios.get('/api/game').then(function (response) {
            game.meta = response.data.meta;
            game.empire = response.data.empire;
            game.planets = response.data.planets;
        });
    },

    router // router is in separate file but nothing special
});

main.blade.php

<router-view :meta="meta" :empire="empire" :planets="planets"></router-view>

我的 Component.vue 文件的脚本部分

export default {
  data: function() {
    return {

    }
  },

  props: {
    meta: {
      type: Object
    },
    empire: {
      type: Object
    },
    planets: {
      type: Array
    }
  }
}

有什么想法吗?提前致谢。

【问题讨论】:

  • imgur.com/a/QbYfB - 我的 Vue 开发工具的图像,其中选择了路由器组件。

标签: laravel vue.js vuejs2 vue-component vue-router


【解决方案1】:

由于您的数据是异步加载的,所以当my Component.vue 呈现父组件中的数据时,您的数据可能不存在。因此,您需要检查您的数据是否已加载。你可以试试这段代码:

{{ meta != null && meta.name }}

PS:你的created 钩子应该是:

 created() {
    axios.get('/api/game').then((response) => {
        this.game.meta = response.data.meta;
        this.game.empire = response.data.empire;
        this.game.planets = response.data.planets;
    });
},

【讨论】:

    【解决方案2】:

    router-view 是来自view-router 的组件,它可以帮助渲染named views。您不能将帝国和行星传递给它,因为它们是您组件的道具。

    您必须具有以下类型的代码才能将帝国和行星传递给您的组件:

    <my-component :meta="meta" :empire="empire" :planets="planets"></my-component>
    

    您可以查看有关此here 的更多详细信息。

    【讨论】:

    • 我正在使用带有
    • @TimTheEnchant3r 我不确定你的用例,你可以看一个例子here,其中item是一个组件。
    • 你仍然可以将 prop 传递给router-view
    猜你喜欢
    • 2023-03-03
    • 1970-01-01
    • 2022-06-12
    • 1970-01-01
    • 2019-10-04
    • 2019-07-27
    • 2017-09-20
    • 1970-01-01
    • 2019-04-20
    相关资源
    最近更新 更多