gpt4 book ai didi

vue.js - 在Vue中捕获计算属性中的错误

转载 作者:行者123 更新时间:2023-12-03 08:06:34 25 4
gpt4 key购买 nike

在VueJS中,我有一个vuex存储getter,它可能会引发ErrorOneErrorTwo类型的错误。

// myGetter.js
export class ErrorOne extends Error {}
export class ErrorTwo extends Error {}

export default () => {
if (...) {
throw new ErrorOne()
}
if (...) {
throw new ErrorTwo()
}
return ...
}

在Vue组件的计算属性中,我正在使用此 setter/getter ,但我想在try catch块中处理这些错误。

// MyComponent.vue
import { ErrorOne, ErrorTwo } from '.../myGetter'

export default {
...,
data() {
return {
errorOne: false,
errorTwo: false
}
},
computed: {
myGetterComputed() {
try {
const value = this.$store.getters['.../myGetter']
this.errorOne = false // Unexpected side effect
this.errorTwo = false // Unexpected side effect
return value
} catch (err) {
switch (err.constructor) {
case ErrorOne:
this.errorOne = true // Unexpected side effect
break
case ErrorTwo:
this.errorTwo = true // Unexpected side effect
break
}
}
}
}

}

但是eslint告诉我 [eslint] Unexpected side effect in "myComputedGetter" computed property. [vue/no-side-effects-in-computed-properties]

在用例中,处理Vue计算属性错误的正确方法是什么?

我应该将 myGetterComputed移至数据并使用watch方法来处理更新吗?

最佳答案

如果我直接回答您的问题,我可以告诉您eslint正在使用this rule警告您有关意想不到的副作用。根据eslint-plugin-vue文档

It is considered a very bad practice to introduce side effects inside computed properties. It makes the code not predictable and hard to understand.



基本上,我们需要记住的是,当有大量逻辑与我们如何处理模板内的数据相关时,应该使用计算属性。因此,您不应该在已计算的属性逻辑中更新任何属性/数据。

如果您提供了您要达到的目标的详细示例,我想进一步为您提供帮助

关于vue.js - 在Vue中捕获计算属性中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54228331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com