【问题标题】:Why is my computed property not computing?为什么我的计算属性不计算?
【发布时间】:2018-07-29 09:45:07
【问题描述】:

下面是一个单文件的 Vue.js 模板。 note 对象作为道具传递给模板,包括audio_lengthid

<template>
    <span v-show="note.audio_length > 0" class="audio-element-wrapper">
        <audio controls preload="none">
            <source :src="audioURL" type="audio/webm">
            Your browser does not support the audio element.
        </audio>
        <span>
        ({{note.audio_length}}s)
            </span>
    </span>
</template>

<script>
module.exports = {
    mounted: function() {
        console.log("mounted audioelement", this.note.id);
    },

    props: ['note'],

    computed: {
        audioURL: function() {
            return "/notes/getAudio/" + this.note.id;
        }
    }
};
</script>

但是,当我加载组件时,计算出的audioURL 会产生/notes/getAudio/undefined。显然,它在 note 属性加载之前运行。花括号内的代码被正确解释。如何将src 属性绑定到正确计算的 url?

【问题讨论】:

  • 确保您在父组件中传递了注释,如 否则您将收到此错误..并且还要检查您的浏览器控制台。对于this.note
  • 我正在使用您描述的语法调用模板。当我运行模板时,花括号中的文本会正确呈现。 {{note.audio_length}} 按预期出现。控制台显示mounted audioelement undefined
  • 只需记录整个 this.note 而不是 this.node.id,这样您就可以看到整个 json 对象。我怀疑它可能没有 id 密钥
  • 你能说明prop的值是如何在parent中设置的吗?

标签: vue.js vuejs2 vue-component computed-properties


【解决方案1】:

我想这不起作用,因为您的 audioURL 计算值返回的路径没有您的文件格式。

尝试改变你的计算:

computed: {
    audioURL: function() {
        return "/notes/getAudio/" + this.id + ".webm";
    }
}

为了更好的调试,我建议你安装 vue-devtools

【讨论】:

  • 谢谢。我正在使用 vue-devtools。当我打开组件时,它会显示所有数据。此外,该文件不以 .webm 结尾。 /notes/getAudio/1 是一个 REST 端点。
【解决方案2】:

解决方案 1 (vue 2.x)

如果您想将对象属性作为道具传递,那么您必须使用v-bind 指令,请参阅此处的docs

我想在你的父组件中你有类似的数据属性:

data: function () {
  return {
    note: {
      audio_lenght: 100,
      id: 12
    }
  }

然后将你的组件写成:

<your-component v-bind='note'></your-component> 

在 YourComponent.vue 中:

...
props: ['id', 'audio_lenght']
...

computed: {
    audioURL: function() {
        return "/notes/getAudio/" + this.id;
    }
}

解决方案 2

把你的组件写成:

<your-component :note='note'></your-component> 

在 YourComponent.vue 中:

props: {
  note: {
    type: Object
  }
},
computed: {
  audioURL: function() {
    return "/notes/getAudio/" + this.note.id;
  }
}

【讨论】:

  • 使用不带 prop 的 v-bind 只会将整个对象绑定到组件。冒号表示法是 v-bind 的简写。这样我就可以拥有对象而不污染命名空间。
  • 我已使用替代解决方案(解决方案 2)更新了我的答案。当道具是一个对象时,我认为 v-bind 冒号快捷方式不起作用,至少我无法使用冒号快捷方式传递对象。我希望它现在更有意义。
【解决方案3】:

感谢大家的帮助。事实证明,问题并不在于 Vuejs本身。是浏览器问题。即使 src 元素实际上已被修改,它也不会更新元素的操作,直到您调用 .load()

因此,有效的解决方案如下:

<template>
<span v-show="note.audio_length > 0" class="audio-element-wrapper">
    <audio ref="player" controls preload="none">
        <source :src="audioURL" type="audio/webm">
        Your browser does not support the audio element.
    </audio>
<span>
</template>

然后,在脚本中:

updated: function() {
    this.audioURL = "/notes/getAudio/" + this.note.id;
    this.$refs.player.load();
},

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 2019-02-23
    • 2017-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多