如何在 VueJS 中使用滑鼠懸停呼叫函式?


當滑鼠懸停在 div 或元素上時,有時需要顯示一些資訊。這些資訊或資料在滑鼠懸停時顯示。因此,為了顯示這些資料,我們基本上使用 JS 函式 @mouseover 來顯示資料。

在本例中,我們將建立一個 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 檔案建立了一個完整的程式碼。

更新於:2023年4月13日

2K+ 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告