Home > database >  parameter function in v-model vue 3
parameter function in v-model vue 3

Time:12-02

Hi I would like to use a function in a v-model (in Vue 3) like this :

<template>
  <input v-model="sayHello('Jhon')">
</template>

<script>
export default{
  methods:{
    sayHello(name){
      return "Hello "  name
    }
  }
}
</script>

But the code returns this error :

VueCompilerError: v-model value must be a valid JavaScript member expression.

I googled the error and found that you're not allowed to use functions in v-model in vue 3. Does anyone know a way to do so anyway? Thanks in advance.

CodePudding user response:

v-model isn't the right directive to use for handling changes to the input. If you want to call a function upon changes, use the v-on directive with the input event:

<script setup>
const onChange = e => {
  if (e.target.value === 'Jhon') sayHello()
}
const sayHello = () => alert('hello')
</script>

<template>
  <h3>Type <code>Jhon</code></h3>
  <input @input="onChange" />
</template>

demo

  • Related