Mar cel
Mar cel

Reputation: 15

Binding an input value to a value in an array

I would like to output the content of an array, so that the output is according to an entered id. I tried to solve this with v-model, but I cant wrap my head around a solution. For example I enter 123 and the item1 shows up and when I enter 321 the item2.

<template>
    <input v-model="inventar[1].id" />
</template>

<script lang="ts">
    import { defineComponent, reactive } from 'vue'

    interface Inventar {
        id: number,
        name: string,
        size: number
    }

    export default defineComponent({
        name: 'HelloWorld',
        setup() {
            const selected: number = 123;
            const inventar: Array<Inventar> = [];

            inventar.push({ id: 123, name: "item1", size: 25 } as Inventar);
            inventar.push({ id: 321, name: "item2", size: 20 } as Inventar);

            return {inventar,selected}
        }
    })
</script>

For help, I would be grateful.

Upvotes: 0

Views: 165

Answers (1)

drocha87
drocha87

Reputation: 629

I wrote a simple implementation, I really don't know if this is the kind of stuff you're trying to do. codepen now is your mission to apply this to vue 3 and typescript ;)

<template>
  <div id="#app">
    Object: {{ found }}
    <div>
      <input type="text" v-model="search" />
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      inventars: [
        { id: "123", value: "123" },
        { id: "321", value: "321" }
      ],
      search: ""
    };
  },

  computed: {
    found() {
      return this.inventars.find((val) => val.id === this.search);
    }
  }
};

Upvotes: 2

Related Questions