Me gustaría optimizar un método que uso para decidir qué valores mostrar en un cuento. Tengo una tabla que muestra diferentes valores y, además, hay algunos campos de entrada. Los valores seleccionados en el campo de entrada se utilizan para filtrar el contenido de la tabla.
<!-- the input fields--> <v-select placeholder="Index" :options="indexList" v-model="filterTable['indexedValue']" @input="filteringTable"></v-select> <v-select placeholder="Domain" :options="domainList" index="index" label="txt" v-model="filterTable['domainValue']" @input="filteringTable"></v-select> <!-- table --> <table> <tbody> <tr v-for="(value, i) in filteringTable()" :key="value.id"> ...<!-- values shown here--> </table>Los valores seleccionados en los campos de entrada están limitados a la tabla de filtros de objetos.
data () { return { filterTable: {} } }Y el método que se llama en la entrada se define de la siguiente manera:
filterTable () { var newLinks = this.links // object containing all the info we want to show in the table if (this.filterTable['indexedValue'] != null && this.filterTable['indexedValue'] !== undefined) { newLinks = newLinks.filter(l => l.post.indexed === this.filterTable['indexedValue']) } if (this.filterTable['domainValue']) { newLinks = newLinks.filter(l => l.tag.domain === this.filterTable['domainValue']) } return newLinks } (mi código tiene 2 declaraciones if más que verifican el valor dado por otros campos de entrada, pero también siguen la misma lógica anterior)
Este código funciona y filtra la tabla, pero como puede ver, hay dos declaraciones if en él y me pregunto si hay algunas formas que pueda seguir para hacerlo más eficiente/optimizado.
¡Cualquier consejo es muy apreciado!
Bueno, es mejor usar computed aquí en lugar de métodos. También cambié el nombre de su función porque podría haber un problema con los nombres porque son los mismos:
computed: { filter_table() { return this.filterTable["domainValue"] ? this.links.filter(l => l.tag.domain === this.filterTable["domainValue"]) : this.links.filter( l => l.post.indexed === this.filterTable["indexedValue"] ); } }; <tr v-for="(value, i) in filter_table" :key="value.id">Esto debería hacer el trabajo.
Tampoco necesita cosas como var newLinks = this.links , puede ir directamente con this.links.filter() . Filter le devuelve una nueva matriz con los valores filtrados.
Editar:
Dijo que desea filtrar si se cumplen ambas condiciones:
computed: { filter_table() { return this.links.filter( (l) => l.tag.domain === this.filterTable["domainValue"] && l.post.indexed === this.filterTable["indexedValue"] ); };