zoukankan      html  css  js  c++  java
  • vue方法中访问调用该方法的html元素示例

    <div id="app">
        <input type="text" v-on:keyup="onlyNum($event)">
    </div>
    
    <script>
    new Vue({
        el:"#app",
        methods: {
            onlyNum: function (event){
                event.target.value=event.target.value.replace(/[^d]/g,'');
            }
        }
    })
    </script>

     相当于:

    <div id="app">
        <input type="text" onkeyup="onlyNum(this)">
    </div>
    
    <script>
            function onlyNum(obj){
                obj.value = obj.value.replace(/[^d]/g,'');
            }
    </script>

     js 原生代码的 “this” 相当于上面vue中 “event.target” 。js中“事件绑定this”,this指的是调用该函数的html元素;但vue的this指的是vue的对象本身,属于js对象“方法中绑定this”的情形;如果要访问调用该函数的html元素,只能用js的event对象中的target属性。

    JavaScript this 关键字

    注意:event是js的对象!

    Event 对象代表事件的状态,比如事件在其中发生的元素、键盘按键的状态、鼠标的位置、鼠标按钮的状态。

    target 事件属性可返回事件的目标节点(触发该事件的节点),如生成事件的元素、文档或窗口。

    event对象知识见这里

    event.target见这里

  • 相关阅读:
    GIT 相关
    createFile
    值传递、指针传递、引用传递
    Sightseeing trip
    find the longest of the shortest
    Laurenty and Shop
    Dima and Lisa
    Marina and Vasya
    Kolya and Tanya
    Two Substrings
  • 原文地址:https://www.cnblogs.com/qingsong/p/11575485.html
Copyright © 2011-2022 走看看