簡體   English   中英

數據更改時Vue不會更新

[英]Vue doesn't update when data changes

我有一個頁面,我稱之為domain.com/subpage?soundfile=something

在我的 fetch 方法中,我使用來自 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>

工作版本:必須使用 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>

您需要告訴音頻標簽加載完成。

如果你不太了解 nuxt,但說它類似於 vue 每當 this.recording 使用 watch 更改時,你可以在 aduio 標簽上運行 .load() 。

例如。

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

我認為您錯過的一件主要事情是添加方法塊:

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 實例,更改不會反映在模板中。

問候

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM