Computed 属性 未触发(添加到 Set)

Computed property not triggered (add to Set)

免责声明:javascript

的新手

我只是试图通过以下方式跟踪组件中的所有当前错误,但我没有明白我做错了什么。每次用户名更改时,我的错误集都会更新,也就是说,我基于 errors 集计算的 属性 displayErrors 也应该更改:

Html分量

<ol v-if="displayErrors">
  <li v-for="e in errors" v-bind:key="e">
    {{ e }}
  </li>
<ol>

数据

data: function () {
    return {
      username: "",
      errors: new Set(),
    }
  }

观察者和方法

watch: {
    username: function (username) {
      this.checkUsernameAvailability(username)
    }
  },
  methods: {
    async checkUsernameAvailability(username) {
      const errorCode = 'usernameNotAvailable'

      try {

        const response = await this.$apollo.query({ query: GET_USERS_QUERY })
        const users = response.data.users

        const usernames = users.map((user) => { return user.username })
        
        if (usernames.includes(username)) {
          this.errors.add(errorCode)
        } else {
          this.errors.delete(errorCode)
        }
        
        // trying to force the computed property
        this.$forceUpdate()

      } catch (error) {
        console.log(error)
        return false
      }
    }
  }

计算属性

computed: {
    displayErrors: function() {
      console.log('triggered', this.errors.size)
      return this.errors.size > 0
    }
  }

提前致谢!

Set Vue无法观察,只能观察普通对象

docsdata 属性 的解释(这也适用于计算属性):

The data object for the Vue instance. Vue will recursively convert its properties into getter/setters to make it "reactive". The object must be plain: native objects such as browser API objects and prototype properties are ignored. A rule of thumb is that data should just be data - it is not recommended to observe objects with their own stateful behavior.

您应该使用数组来存储错误列表。