如何在VueJS中通过鼠标悬停调用函数
在悬停在一个div或元素上时,有时我们需要显示一些信息。当鼠标悬停在上面时,这些信息或数据会被显示出来。因此,为了显示这些数据,我们基本上使用JS函数@mouseover来显示数据。
在上述特定情况下,我们将创建一个鼠标悬停函数,该函数将在悬停时返回数据。请参考下面的示例以获得更多说明。
语法
下面是在Vue.js中通过鼠标悬停调用函数的语法:
mouseOver: function(){
this.active = !this.active;
}
这里, mouseOver 是一个在鼠标悬停时被调用的函数。当一个HTML元素触发调用这个函数的事件时,这个函数会在调用它的对象中切换一个叫做”active”的属性的值。
如果”active”属性当前为false,那么这个函数会将它设置成true。如果它当前为true,那么这个函数会将它设置为false。
示例
在你的Vue项目中创建两个文件app.js和index.html。下面的代码片段给出了这两个文件的文件和目录。将下面的代码片段复制粘贴到你的vue项目中并运行vue项目。你将在浏览器窗口上看到下面的输出。
- 文件名 – app.js
-
目录结构 — $project/public — app.js
// Calling the mouseover function on hover
var demo = new Vue({
el: '#demo',
data: {
active: false
},
methods: {
mouseOver: function(){
this.active = !this.active;
}
}
});
-
文件名 – index.html
-
目录结构 — $ project/public — index.html
<!DOCTYPE html>
<html>
<head>
<title>
VueJS | v-else directive
</title>
<!-- Load Vuejs -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="demo">
<p v-show="active" style="text-align: center;">Hi... you hovered on the text !</p>
<h1 @mouseover="mouseOver" style="text-align: center;">Hover over me!</h1>
</div>
<template id="child">
<input type="text" v-bind:value="value" v-on:input="updateValue($event.target.value)">
</template>
<script src='app.js'></script>
</body>
</html>
运行以下命令以获取以下输出 −
C://my-project/ > npm run serve
完整的代码
这是从上面两个文件app.js和index.html中组合的代码。现在,我们可以将这段代码作为一个HTML程序来执行。
<!DOCTYPE html>
<html>
<head>
<title> VueJS | v-else directive </title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="demo">
<p v-show="active" style="text-align: center;">Hi... you hovered on the text !</p>
<h1 @mouseover="mouseOver" style="text-align: center;">Hover over me!</h1>
</div>
<template id="child">
<input type="text" v-bind:value="value" v-on:input="updateValue($event.target.value)">
</template>
<script>
// Calling the mouseover function on hover
var demo = new Vue({
el: '#demo',
data: {
active: false
},
methods: {
mouseOver: function() {
this.active = !this.active;
}
}
});
</script>
</body>
</html>
在这篇文章中,我们演示了如何在Vue.js中使用鼠标悬停调用函数。为了完成这个任务,我们需要两个文件app.js和index.html,并使用<script>
标签在index.html文件中添加app.js文件。最后,我们将app.js和index.html合并成一个HTML文件,创建了一个完整的代码。