首页 > 解决方案 > 如何仅在 VueJS 中的 API 初始加载后观看?

问题描述

我从 API 获取数据,我用这些数据在我的组件中填充表单。我只需要在初始填充数据后触发观察者。就像以异步方式一样。但是观察者会立即被触发。只有在初始填充数据后更改了任何值时,我才需要禁用更新按钮。

<template>
  <div id="app">
    <input type="text" v-model="user.userId" /> <br />
    <br />
    <input type="text" v-model="user.title" /> <br />
    <br />
    <button :disabled="isDisabled">Update</button>
  </div>
</template>

<script>
export default {
  name: "App",
  watch: {
    user: {
      handler(oldVal, newVal) {
        if (oldVal != newVal) {
          this.isLoaded = false;
        }
      },
      deep: true,
    },
  },
  computed: {
    isDisabled() {
      return this.isLoaded;
    },
  },
  async created() {
    await fetch("https://jsonplaceholder.typicode.com/todos/1")
      .then((response) => response.json())
      .then((json) => {
        this.user = json;
        this.isLoaded = true;
      });
  },
  data() {
    return {
      user: {
        userId: 0,
        id: 0,
        title: "",
        completed: false,
      },
      isLoaded: true,
    };
  },
};
</script>

我已经提到了 Vue,等待 Watch手表是异步的吗?Vue.js How to watcher before mounted() ,无法从手表获取数据,但我无法关注。

这是一个预览:https ://codesandbox.io/embed/great-euler-skd3v?fontsize=14&hidenavigation=1&theme=dark

标签: javascriptvue.js

解决方案


这需要通过一些条件来确定。

isLoaded已经服务于确定初始加载状态的目的,但名称令人困惑,因为它确定数据加载。

有可能:

  watch: {
    user: {
      if (this.isLoading && oldVal != newVal) {
        this.isLoading = false;
      }
      ...

观察者不需要deep并且在不需要时可以不被观察:

async created() {
  let unwatchUser = this.$watch('user', (oldVal, newVal) => {
    if (this.isLoading && oldVal != newVal) {
      this.isLoading = false;
      unwatchUser();
    }
  })
  ...

指定数据尚未加载的常用方法是将其设置为null,即无值。这不需要isLoading标志或观察者。如果null由于引用的对象属性而不需要,则可以通过可选的链接和条件渲染来克服:

  <div v-if="user">
      <input type="text" v-model="user.userId" />
      ...
  <div v-else class="spinner"/>

推荐阅读