数据更改时Vue不会更新

时间:2020-11-10 04:37:33

标签: javascript vue.js nuxt.js

我有一个称为 domain.com/subpage?soundfile=something

的页面

在获取方法中,我使用url中的查询来实际获取数据。根据 console.log ,查询有效,我获取了数据,并将其分配给也有效的 this.recording 。但是,我的跨度和音频元素都不会更新。为什么?

<template>
  <div>
    <audio controls>
      <source :key="key" :src="recording" type="audio/mp3" />
    </audio>
    <span :key="key">{{ recording }}</span>
  </div>
</template>

<script>
const axios = require("axios").default;

export default {
  data() {
    return {
      key: 0,
      recording: ""
    };
  },
  async fetch(context) {
    const ip = await axios.get(
      "somebackend/?soundfile=" + context.query.soundfile
    );

    this.recording = ip.data[0].file.url;
    console.log(this.recording); // gives me the correct url/mp3 file
    this.key++; // should update the audio element and the span but doesn't
  }
};
</script>

3 个答案:

答案 0 :(得分:0)

工作版本: 必须使用asyncData而不是fetch。

<template>
  <div>
    <audio controls>
      <source :src="soundfile" type="audio/mp3" />
    </audio>
    <span>{{ soundfile }}</span>
  </div>
</template>

<script>
const axios = require("axios").default;

export default {
  async asyncData(context) {
    const ip = await axios.get(
      "somebackend/?soundfile=" + context.query.soundfile
    );

    return {
      soundfile: ip.data[0].file.url
    };
  }
};
</script>

答案 1 :(得分:0)

您需要告诉音频标签加载已完成。

如果您不太了解nuxt,但是说它类似于vue 每当使用watch更改此记录时,您都可以在aduio标签上运行.load()。

例如。

<audio controls ref='player'>
this.$watch('record', () => {
                this.$refs.player.load()
            })

答案 2 :(得分:-1)

我认为您错过的一件主要事情是添加方法块:

export default {
  data() {
    return {
      key: 0,
      recording: ""
    };
  },
  methods: {
    async fetch(context) {
      const ip = await axios.get(
        "somebackend/?soundfile=" + context.query.soundfile
      );
      this.recording = ip.data[0].file.url;
      console.log(this.recording); // gives me the correct url/mp3 file
      this.key++; // should update the audio element and the span but doesn't
    }
  },
};
</script>

由于它不在方法块中,因此对this的引用不是您所期望的,即vue实例。因此,密钥不会更新,并且会记录到控制台,但是由于它未绑定到vue实例,因此更改不会反映在模板中。

致谢