【发布时间】:2020-12-05 13:36:51
【问题描述】:
免责声明:javascript 新手
我只是试图通过以下方式跟踪组件中的所有当前错误,但我不明白我做错了什么。每次用户名更改时,我的错误集都会更新,也就是说,我的计算属性 displayErrors 基于 errors 集也应该更改:
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
}
}
提前致谢!
【问题讨论】:
-
new set() 不适用于 Vue。最好使用 Array 来实现您想要的。
标签: vue.js vuejs2 vue-component computed-properties