【问题标题】:Vue component prop value is undefined when accessing from template从模板访问时,Vue组件道具值未定义
【发布时间】:2017-05-17 12:22:24
【问题描述】:

我创建了 2 个 Vue 组件:

Vue.component('vimeo', {
    template: '<iframe src="https://player.vimeo.com/video/' + this.videoId + '" width="640" height="360" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>',
    props: ['videoId']
});

Vue.component('videos', {
    template: '<div id="videos">' + 
                '<div v-for="videoId in videoIds">' +
                    '<vimeo :video-id="videoId"></vimeo>' +
                '</div>' +
              '</div>',
    computed: {
        videoIds: function() {
            return store.state.videoIds;
        }
    }
});

但是,this.videoId 在“vimeo”组件模板中始终未定义。如果我将模板更改为:

<h1>{{ videoId }}</h1>

prop 值可以正常显示。

我已经在互联网上搜索了这个问题的解决方案,但不幸的是,我没有找到任何解决方案。

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    您拥有的代码基本上是在模板定义时尝试使用this.videoId,在任何组件初始化之前。

    您需要做的是bind videoId 值,以便在渲染时间进行翻译。我会使用计算属性来执行此操作,因为您需要连接 vimeo URL 前缀。

    类似:

    computed: {
      videoUrl() { return 'https://player.vimeo.com/video/' + this.videoId; }
    },
    template: '<iframe :src="videoUrl" width="640" height="360" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>'
    

    注意:src 中的冒号用于动态绑定。 See the docs for more info on this.

    【讨论】:

      猜你喜欢
      • 2020-08-03
      • 2020-08-04
      • 2018-06-03
      • 2018-09-23
      • 2021-12-12
      • 1970-01-01
      • 2018-04-10
      • 1970-01-01
      相关资源
      最近更新 更多