A
A
Anastasia2020-09-21 17:52:24
Vue.js
Anastasia, 2020-09-21 17:52:24

How to break into adequate vue components?

Hello!

I'm a total newbie to Vue, and honestly, I couldn't find an answer (or just apparently formulate it correctly) on the internet.

I have two components (html selects), one of them is multiple, and they have a different value, in fact one is Array, and the other is String, but their html structure is outrageously the same (violates the DRY principle)

<template>
  <label>
    {{ select.label }}
    <Error v-model="value"/>
    <select v-model="value" :multiple="select.isMultiple" :name="select.label">
      <option disabled value="">Выберете один</option>
      <option v-for="(option, i) in select.options" :key="i" :value="option">
      {{ option }}
      </option>
    </select>
  </label>
</template>


Prompt how it is more correct to "pack" select into components.
I would also appreciate useful links and constructive criticism.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-09-21
@anastasiaun

Make a generic component with a parameter that will determine the number of values ​​available for selection:

props: {
  multiple: Boolean,
  ...
},
computed: {
  placeholder() {
    return `Выберите ${this.multiple ? 'несколько значений' : 'одно значение'}`;
  },
  innerValue: {
    get() {
      const v = this.value;
      return this.multiple || this.options.includes(v) ? v : '';
    },
    set(val) {
      this.$emit('input', val);
    },
  },
},

<select v-model="innerValue" :multiple="multiple">
  <option disabled value="" v-text="placeholder"></option>
  <option v-for="n in options">{{ n }}</option>
</select>

https://jsfiddle.net/cgknyLd0/2/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question