Vue 模板语法
封面图
•
2026-03-27
•
Vue
8
0
0
0
Vue 模板语法是 Vue.js 的核心特性之一,它允许你使用类似 HTML 的模板语言来构建用户界面。Vue 的模板语法本质上是 JavaScript 表达式的超集,可以在模板中进行数据绑定、条件渲染、循环、事件处理等操作。 以下是 Vue 模板语法的一些常见用法和关键概念: --- ## 1. **数据绑定(Data Binding)** ### a. 插值(Interpolation) ```html {{ message }} ``` - `message` 是在 `data` 中定义的变量。 - 可以使用 JavaScript 表达式: ```html {{ firstName + ' ' + lastName }} ``` ### b. 单向绑定(v-bind) ```html <img :src="imageSrc"> <!-- 等价于 --> <img v-bind:src="imageSrc"> ``` - 用于绑定属性,如 `src`, `class`, `style` 等。 --- ## 2. **指令(Directives)** Vue 提供了一些以 `v-` 开头的特殊属性,称为“指令”,用于在模板中执行特定的操作。 ### 常见指令: #### a. `v-if` / `v-show` ```html <p v-if="show">显示内容</p> <p v-show="show">显示内容</p> ``` - `v-if` 是条件渲染,会根据条件动态添加或移除 DOM 节点。 - `v-show` 是通过 CSS 控制显示/隐藏。 #### b. `v-for`(循环) ```html <ul> <li v-for="item in items" :key="item.id">{{ item.text }}</li> </ul> ``` - 通常需要配合 `:key` 使用以提高性能和避免问题。 #### c. `v-on`(事件监听) ```html <button @click="increment">点击</button> <!-- 等价于 --> <button v-on:click="increment">点击</button> ``` - `@` 是 `v-on:` 的简写。 #### d. `v-model`(表单绑定) ```html <input v-model="message"> <textarea v-model="message"></textarea> <select v-model="selected"> <option value="1">选项1</option> <option value="2">选项2</option> </select> ``` - 实现双向数据绑定。 #### e. `v-text` / `v-html` ```html <div v-text="text"></div> <div v-html="htmlContent"></div> ``` - `v-text` 会将数据作为文本插入,不会解析 HTML。 - `v-html` 会将数据作为 HTML 渲染。 --- ## 3. **条件与循环** ### 条件判断 ```html <div v-if="type === 'A'">类型 A</div> <div v-else-if="type === 'B'">类型 B</div> <div v-else>其他类型</div> ``` ### 循环 ```html <ul> <li v-for="(item, index) in list" :key="index"> {{ index }}: {{ item.name }} </li> </ul> ``` --- ## 4. **计算属性(Computed Properties)** 虽然不是模板语法本身,但常用于模板中: ```html <p>{{ fullName }}</p> ``` ```javascript computed: { fullName() { return this.firstName + ' ' + this.lastName; } } ``` --- ## 5. **过滤器(Filters)**(Vue 2 特性) ```html {{ message | capitalize }} ``` ```javascript filters: { capitalize(value) { return value.charAt(0).toUpperCase() + value.slice(1); } } ``` > 注意:Vue 3 已移除过滤器功能,建议用计算属性代替。 --- ## 6. **模板中的表达式** Vue 模板支持大部分 JavaScript 表达式,比如: ```html {{ number + 1 }} {{ message.split('').reverse().join('') }} {{ isOk ? 'Yes' : 'No' }} ``` --- ## 7. **组件(Component)** 你可以将 Vue 模板组织成组件,并在其他模板中使用: ```html <my-component></my-component> ``` --- ## 8. **作用域插槽(Scoped Slots)** 用于从子组件传递数据到父组件的模板中: ```html <template v-slot:default="slotProps"> {{ slotProps.item }} </template> ``` --- ## 9. **自定义指令(Custom Directives)** 可以注册全局或局部的自定义指令: ```javascript // 全局指令 Vue.directive('focus', { inserted: function (el) { el.focus(); } }); ``` ```html <input v-focus> ``` --- ## 10. **模板语法注意事项** - 不要在模板中执行复杂逻辑(如循环、函数调用),应使用计算属性或方法。 - 避免直接修改 `props`,因为它们是只读的。 - 使用 `key` 属性来优化 `v-for` 的性能。 --- 如果你有具体的使用场景或想了解某个特定语法(如 `v-model`、`v-for`、`v-if` 等),我可以提供更详细的示例和解释。
上一篇:
Vue测试
下一篇:
Vue 响应式基础
标题录入,一次不能超过6条
留言
评论