vue2使用oninput绑定事件报错:

         <input type="text" id='input' :value="msg" οninput="oninputHandler()">

(index):1 Uncaught ReferenceError: oninputHandler is not defined
    at HTMLInputElement.oninput ((index):1:1)

源码如下:

<template>
  <div>
    <h2>深入v-model</h2>
    <input type="text" v-model="msg">
    <span>{{ msg }}</span>
    <hr/>
    <h2>v-model实现原理</h2>
      <input type="text" id='input' :value="msg" oninput="oninputHandler()">
    <span>{{ msg }}</span>
  </div>
</template>

<script>

export default {
  name: "ModelTest",
  data() {
    return {
      msg: "HI - HI"
    }
  },
  methods: {
    oninputHandler(e) {
      let changeVal = document.getElementById("input");
      this.msg = changeVal.value;
      console.log(changeVal.value)
    }
  }
}
</script>

<style scoped>

</style>

分析 :

在html练习:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<input type="text" id="input" oninput="handleInput()"></input>
<span id="num"></span>
<span id="num"></span>
<script>
    function handleInput(e) {
// 处理事件代码

        var changeVal = document.getElementById("input");
        var showVal = document.getElementById("num");
        showVal.innerText = changeVal.value;
        console.log(changeVal.value)

    }
</script>


</body>
</html>

运行:监听oninput事件完全是OK的 

解决:

错误写法:

在vue2中这样写是没有作用的:οninput=‘function()’, 

oninput正确写法: @input="oninputHandler()

<input type="text" id='input' :value="msg" @input="oninputHandler()">

 或者: v-on:input="oninputHandler()"

      <input type="text" id='input' :value="msg" v-on:input="oninputHandler()">

执行效果:

扩展:onchange事件实现 

错误写法:

在html中onchange事件,在vue中也是不能直接写成οnchange='func()' ,
否则也会报类似的错,

VM7180 model:18 Uncaught ReferenceError: oninputHandler is not defined
    at HTMLInputElement.onchange (VM7180 model:18:2)

正确写法:
@change='func()'

Logo

前往低代码交流专区

更多推荐