Home > Software design >  How to watch for change on a specific input in list of inputs in Vue 3
How to watch for change on a specific input in list of inputs in Vue 3

Time:11-29

I am attempting to set up a vue 3 watcher that watches for changes to input fields in a v-for list. I set up an array of objects, each with a type. I want to add input to the field with the type "owl", then watch for a change only on that field. However, when I bind the input field in the loop to inputValue then add text to the field with label "Owl", my inputted text shows up on all of the inputs. How can I go about setting up the input field to only display text on input "Owl" in the loop?

Here is my code so far:

<template>
  <div >
    <dl >
      <div v-for="input in inputs" :key="input.label" >
        <dt >
          <div >
            <span>{{ input.label }}</span>
          </div>
        </dt>

        <dd >
          <input
            v-model="inputValue"
          />
        </dd>
      </div>
    </dl>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch, toRaw } from "vue";

const inputValue = ref()

const inputs = ref([
  { label: "Dog", type: "dog" },
  { label: "Cat", type: "cat" },
  { label: "Owl", type: "owl" },
  { label: "Rabbit", type: "rabbit" },
  { label: "Horse", type: "horse" },
]);


watch(inputValue, () => {
  console.log(inputValue.value)
})
</script>

CodePudding user response:

Not sure I'm following but if you only want to bind the model to the owl type you could use conditional rendering:

<input v-if="input.type === 'owl'" v-model="inputValue" />
<input v-else :value="input.type" />
  • Related