[Vuejs]-Reading multiple values from reusable child components in it's parent component in Vue 3

3πŸ‘

βœ…

If you want to control this through a single variable, you should change the component structure and not use a v-model. You can set the input event that you will send from within the component, by capturing it in the parent, whenever you want. It is very difficult to handle this with a single variable in a structure bind using v-model.

In the component:

const emit = defineEmits(['input'])

function emitValue(e) {
  let value = e.target.value
  if (props.modelModifiers.capitalize) {
    value = value.charAt(0).toUpperCase() + value.slice(1)
  }
  emit('input', value)
}

In App.vue:

<script setup>
import { ref } from 'vue'
import MyComponent from './MyComponent.vue'
  
const myText = ref('')
const inputHandler = (input) => {
// do some logic and set value of myText
}
</script>

<template>
  This input capitalizes everything you enter:<br />
  <MyComponent @input="inputHandler" /><br />
  <MyComponent @input="inputHandler" />
</template>
πŸ‘€Tanzer Atay

1πŸ‘

Why not define two MyText variables?

const myText1 = ref('')
const myText2 = ref('')
</script>

<template>
  This input capitalizes everything you enter:<br />
  <MyComponent v-model.capitalize="myText1" /><br />
  <MyComponent v-model.capitalize="myText2" />
</template>

This is straightforward and I would prefer a simple way instead of some tricking with Vue.js Reactivity/Events to achieve the same on one variable.

You could also use an object, if you don’t want to have two variables.

Like this:

const myText = ref({ text1: '', text2: ''})

<template>
  This input capitalizes everything you enter:<br />
  <MyComponent v-model.capitalize="myText.text1" /><br />
  <MyComponent v-model.capitalize="myText.text2" />
</template>
πŸ‘€Tolbxela

Leave a comment