猿问

找到更好的方法来查看对象是否已填充字段

我在 Vue 中得到了过滤器。


模板:


<b-button v-if="filterFilled()" @click="clearFilter">

    Clear

</b-button>

数据:


data () {

      return {

        filter: {

          price_from: '',

          price_to: '',

          surface_from: '',

          surface_to: '',

          floor: '',

          type: '',

          structure: '',

        },

      }

    },

我检查的方法是过滤器脏了:


filterFilled(){

        return (this.filter.price_from || this.filter.price_to || this.filter.surface_to || this.filter.surface_from ||

          this.filter.floor || this.filter.type || this.filter.structure)

      },

这工作正常,但我的问题是,是否存在更好的方法来询问对象是否已填充道具?


森林海
浏览 128回答 2
2回答

MMTTMM

您可以使用以下方法检查是否this.filter至少有一个truthy值somefilterFilled() {&nbsp; return Object.values(this.filter).some(v => v)}

幕布斯7119047

对于检查组件中数据的方法,您通常应该更喜欢计算属性而不是方法,因为它们的性能更高,并且仅在其某些依赖项更改时才调用:...data () {&nbsp; &nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; &nbsp; filter: {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; price_from: '',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; price_to: '',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; surface_from: '',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; surface_to: '',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; floor: '',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type: '',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; structure: '',&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; },&nbsp; computed: {&nbsp; &nbsp; &nbsp;filterFilled() {&nbsp; &nbsp; &nbsp; &nbsp;// as in @adiga answer, which is great&nbsp; &nbsp; &nbsp; &nbsp;return Object.values(this.filter).some(v => v);&nbsp; &nbsp; &nbsp;}&nbsp; }
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答