如何在 VueJS 中條件停用輸入框?


要移除停用屬性,我們可以使用 VueJS 中提供的 disabled 標籤。disabled 標籤基本上會檢查布林值,並決定是否需要顯示 input 標籤。我們在 app.js 中設定值,並根據切換功能動態更改其值。

要應用 :disabled,我們首先需要建立一個 id 為 'app' 的 div 元素。建立 div 元素後,我們可以透過初始化資料內容將停用屬性應用於該元素。

語法

以下是 Vue.js 中停用輸入框的語法:

@click = "disabled"

示例

首先,我們需要建立一個 Vue 專案。為此,您可以參考此頁面。在您的 Vue 專案中建立兩個檔案 app.js 和 index.html。將下面的程式碼片段複製貼上到您的 Vue 專案中,並執行 Vue 專案。您將在瀏覽器視窗中看到以下輸出。

  • 檔名 - app.js

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

// Setting the default value as false
var app = new Vue({
   el: '#app',
   data: {
      disabled: 0
   }
});
  • 檔名 - 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 style="text-align: center;">
         <h1 style="color: green;">
            Welcome to Tutorials Point
         </h1>
         <b>
            VueJS | v-else directive
         </b>
      </div>
      <div id="app" style="text-align: center;">
         <button @click="disabled = (disabled + 1) % 2">Toggle Enable</button>
         <input type="text" :disabled="disabled == 1">
         <pre>{{ $data }}</pre>
      </div>
      <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 style="text-align: center;">
         <b> VueJS | v-else directive </b>
      </div>
      <div id="app" style="text-align: center;">
         <button @click="disabled = (disabled + 1) % 2">Toggle Enable</button>
         <input type="text" :disabled="disabled == 1">
         <pre>{{ $data }}</pre>
      </div>
      <script>
         
         // Setting the default value as false
         var app = new Vue({
            el: '#app',
            data: {
               disabled: 0
            }
         });
      </script>
   </body>
</html>

當您單擊“切換啟用”按鈕時,輸入欄位將被停用,您將無法輸入任何字元。因此,我們可以切換按鈕來啟用和停用輸入列。

更新於: 2023年4月13日

4K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.