vue中绑定事件的方式
v-on:原生事件名 的方式绑定事件


运行结果
点击按钮后出现如下

下面@click的方式是v-on:事件名的简写方式
v-on:click=""
双引号里面是一个函数写法


调用时候可以直接写上test vue会自动判断test为一个函数然后执行这个函数
也可以写上test()
如下

运行结果

还可以箭头函数传参数


运行结果

不通过传参数的方式 箭头函数内部无法获取到vue实例里面的变量
如下


运行结果

报错了 引用不到myname变量
解决方法
1.将箭头函数改成普通function 加入this.变量值
如下


这时必须执行test2()小括号必须有
运行结果

如果去掉小括号 如下调用写法

运行结果

找不到myname变量
这时需要使用到methods方法
官方推荐做法 将函数统一放到methods下面
methods方法不能使用箭头函数 因为里面this不会指向vue实例 而是undefined
在methods里面定义方法 是官方推荐的 不在data里面定义 会出一定的问题
在methods里面定义的方法 调用时候 加上小括号 或者不加都可以正常运行
如下


运行结果

改成加上小括号

运行结果

总结
vue中要把方法定义在methods里面 是一个对象属性 里面放一堆函数
必须要写成普通function不能是箭头函数 否则会出现this指向undefined
然后函数调用时候 表达式加小括号 不加都可以 不加vue会自动判断表达式是一个function进而执行函数
网友评论