如何在 VueJS 中繫結屬性?


VueJS 中的v-bind 指令可用於將一個或多個屬性或元件 prop 繫結到元素。如果屬性繫結到在 Vue 例項中定義的資料,則由於屬性已繫結,因此可以動態觀察這些資料的變化。

要應用 v-bind 指令,我們將首先建立一個 id 為“app”的 div 元素。建立 div 元素後,可以將v-on: click.middle指令應用於該元素。

語法

我們可以使用以下語法在 Vue.js 中繫結屬性:

v-bind:attribute = "expression"	

這裡“表示式”是我們想要繫結到屬性的值。

示例:實現 v-on:click.middle 指令

在 Vue 專案中建立兩個檔案 app.js 和 index.html。下面給出了這兩個檔案的程式碼片段及其檔案和目錄結構。將以下程式碼片段複製貼上到您的 Vue 專案中並執行該專案。您將在瀏覽器視窗中看到以下輸出。

  • 檔名 - app.js

  • 目錄結構 -- $project/public -- app.js

// Setting the default visiblity to false
var app = new Vue({
   el: '#app',
   data: {
      ifActive: true
   }
})
  • 檔名 - index.html

  • 目錄結構 -- $project/public -- index.html

<!DOCTYPE html>
<html>
<head>
   <script src= "https://cdn.jsdelivr.net/npm/vue/dist/vue.js"> </script>
   <style>
      .active {
         color: blue;
      }
      .error {
         color: red;
      }
   </style>
</head>
   <body>
      <div style="text-align: center;">
         <h1 style="color: green;">
            Welcome to Tutorials Point
         </h1>
         <b>
            v-bind directive(VueJS)
         </b>
      </div>

      <div id="app" style="text-align: center; padding-top: 40px;">
         <button v-on:click="ifActive = !ifActive">
            Click to Toggle
         </button>
            
         <h1 v-bind:class="{active: ifActive, error: !ifActive}">
            Welcome to Tutorials Point
         </h1>
      </div>

      <script src='app.js'></script>
   </body>
</html>

執行以下命令以獲取以下輸出:

C://my-project/ > npm run serve

完整程式碼

<!DOCTYPE html>
<html>
<head>
   <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"> </script>
   <style>
      .active {color: blue;}
      .error {color: red;}
   </style>
</head>
   <body>
      <div style="text-align: center;">
         <h1 style="color: green;"> Welcome to Tutorials Point </h1>
         <b> v-bind directive(VueJS)</b>
      </div>
      <div id="app" style="text-align: center; padding-top: 40px;">
         <button v-on:click="ifActive = !ifActive"> Click to Toggle </button>
         <h1 v-bind:class="{active: ifActive, error: !ifActive}">
            Welcome to Tutorials Point
         </h1>
      </div>
      <script>
         
         // Setting the default visiblity to false
         var app = new Vue({
            el: '#app',
            data: {
               ifActive: true
            }
         })
      </script>
   </body>
</html>

在本文中,我們演示瞭如何在 Vue.js 中繫結屬性。為了執行此任務,我們建立了 app.js 和 index.html 檔案,並使用<script>標籤在 index.html 檔案中包含了 app.js 檔案。最後,我們透過將 app.js 和 index.html 組合成一個 HTML 檔案建立了完整的程式碼。

更新於: 2023年4月13日

2K+ 閱讀量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.