2024-12-09 當按下 建立新筆記 時,才可䠼入 text 及 textarea

2024-12-09 當按下 建立新筆記 時,才可䠼入 text 及 textarea

要實現點擊「建立新筆記」按鈕後才可輸入 texttextarea 的行為,可以透過 Vue.js 的條件控制來完成。例如,可以用布林變數來控制 textareainput 是否禁用 (disabled 屬性),直到按下按鈕後再啟用它們。

以下是實現方式:


修改程式碼

JavaScript

新增一個 isEditing 狀態,初始為 false,按下按鈕後設為 true

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<script>
import { ref, onMounted, onUnmounted } from 'vue';
import autosize from 'autosize';

export default {
setup() {
const text = ref(null); // 初始值為 null
const textarea = ref(null);
const isEditing = ref(false); // 控制是否可以輸入

onMounted(() => {
if (textarea.value) {
autosize(textarea.value);
}
});

onUnmounted(() => {
if (textarea.value) {
autosize.destroy(textarea.value); // 確保在組件卸載時清理資源
}
});

const enableEditing = () => {
isEditing.value = true; // 按下按鈕後啟用輸入
};

return {
text,
textarea,
isEditing,
enableEditing,
};
},
};
</script>

Template

根據 isEditing 狀態,切換 inputtextareadisabled 屬性。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<template>
<p class="s_header">Notes</p>

<div class="notes_container">
<div class="inputBox">
<input
type="text"
required
spellcheck="false"
:disabled="!isEditing"
/>
<span class="labelline">標題</span>
</div>
<div class="inputBox">
<textarea
v-model="text"
ref="textarea"
spellcheck="false"
required
:disabled="!isEditing"
></textarea>
<span class="labelline">筆記</span>
</div>

<div class="btn-container">
<a href="#" class="btn" @click.prevent="enableEditing">建立新筆記</a>
</div>
<div class="footer">筆記應用程式</div>
</div>
</template>

行為說明

  1. 初始狀態
    • isEditingfalseinputtextarea 加上 disabled 屬性,無法輸入。
  2. 按下「建立新筆記」按鈕
    • 呼叫 enableEditing 方法,將 isEditing 設為 true
    • 移除 disabled 屬性,允許輸入。

效果

  • 畫面載入時,inputtextarea 是不可編輯的。
  • 點擊「建立新筆記」按鈕後,inputtextarea 變為可編輯。