Vue 3 add multiple values to an array

Viewed 44

I'm trying to add multiple values the checkedVessels but it doesn't seem to work.

Here's what I tried

Vue template

<tr v-for="vessel in vessels.data" :key="vessel.id">
    <Input type="checkbox" v-model="checkedVessels" :value="vessel.id" />
</tr>

Vue Script

data () {
    return {
        term: '',
        importing: false,
        exporting: false,
        form: this.$inertia.form({
            file: null
        }),
        checkedVessels: []
    }
},

The docs mention what I could do something like this but I'm not sure what I'm doing wrong

https://vuejs.org/guide/essentials/forms.html#checkbox

I know I could implemented it doing something like

<Input type="checkbox" @click="checkedVessels.push(vessel.id)" />

But the docs implementation looks cleaner to me

Edit:

I used input HTML element instead of my custom Input component and it seems to works fine.

Is there anything I can do to update my custom Input component to make it work just like the regular input HTML element?

Input.vue

<template>
<input class="border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 rounded-md shadow-sm" :value="modelValue" @input="$emit('update:modelValue', $event.target.value)" ref="input">
</template>

<script>
export default {
    props: ['modelValue'],

    emits: ['update:modelValue'],

    methods: {
        focus() {
            this.$refs.input.focus()
        }
    }
}
</script>
1 Answers

What about using a computed with getter and setter? This way you can still use v-model:

Input.vue

<template>
  <input v-model="modelComp" ref="input" class="border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 rounded-md shadow-sm">
</template>

<script>
export default {
  props: ['modelValue'],
  computed: {
    modelComp: {
      get: function() {
        return this.modelValue;
      },
      set: function(newValue) {
        this.$emit("update:modelValue", newValue);
      }
    }
  },
  methods: {
    focus() {
      this.$refs.input.focus()
    }
  }
}
</script>

I made the complete example in Playground:

Playground example

Please give it a try and let me know if you find this helpful.

Related