Activity 13: Toggle the Message Visibility When the Button is Clicked
1. Understanding the Goal
我们的目标是在点击按钮时切换消息的可见性。我们将使用 Vue.js 中的 v-if 和 v-else 指令,根据布尔数据属性 ( showMessage ) 有条件地渲染元素。
2. Step-by-Step Instruction
- Step 1: Define a boolean data property
showMessagein the Vue.js component's data. - Step 2: Use the
v-ifdirective to conditionally render a success message whenshowMessageis true. - Step 3: Use the
v-elsedirective to render a prompt message whenshowMessageis false. - Step 4: Add a button and use the
@clickevent handler to toggle the value ofshowMessagewhen the button is clicked.
3. Code Explanation
| 部分 | 说明 |
|---|---|
ref(false) | 定义响应式布尔值,初始为 false,用于控制消息显示与否。 |
showMessage = !showMessage | 点击按钮时取反布尔值,实现开关式切换。 |
v-if="showMessage" | 条件渲染:当为 true 时渲染成功消息元素,否则不渲染。 |
<p class="message success">...</p> | 使用已有的样式类(如绿色背景与边框)来突出提示信息。 |
Click the button to see a message. | 辅助文案,引导用户进行操作(不影响逻辑)。 |