【问题标题】:parameter function in v-model vue 3v-model vue 3中的参数函数
【发布时间】:2022-01-08 09:14:51
【问题描述】:

您好,我想在 v-model(在 Vue 3 中)中使用一个函数,如下所示:

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

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

但代码返回此错误:

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

我用谷歌搜索了这个错误,发现你不允许在 vue 3 中使用 v-model 中的函数。有谁知道这样做的方法吗? 提前致谢。

【问题讨论】:

  • 为什么要绑定一个函数来输入?你希望函数什么时候触发?
  • 我希望函数在值名称(“jhon”)发生变化时触发,就像在 vue 2 中所做的那样。我这样做是因为在我的真实代码中需要格式化数据。

标签: function vue.js vuejs3 v-model


【解决方案1】:

v-model 不是用于处理输入更改的正确指令。如果您想在更改时调用函数,请使用 v-on 指令和 input 事件:

<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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 2021-12-11
    • 2021-11-12
    • 1970-01-01
    • 2018-11-02
    • 2018-06-13
    • 2023-02-03
    相关资源
    最近更新 更多