vue模板实现
Vue 模板实现方法
Vue 模板是 Vue.js 的核心特性之一,用于声明式地将 DOM 绑定至底层 Vue 实例的数据。以下是几种常见的 Vue 模板实现方式:
单文件组件(SFC)模板
使用 .vue 文件格式,将模板、脚本和样式封装在一个文件中:
<template>
<div>
<h1>{{ title }}</h1>
<button @click="handleClick">Click me</button>
</div>
</template>
<script>
export default {
data() {
return {
title: 'Vue Template'
}
},
methods: {
handleClick() {
alert('Button clicked!')
}
}
}
</script>
<style scoped>
h1 {
color: #42b983;
}
</style>
字符串模板
通过 template 选项直接定义模板字符串:
new Vue({
template: `
<div>
<p>{{ message }}</p>
</div>
`,
data: {
message: 'Hello Vue!'
}
})
DOM 内联模板 使用 HTML 中的 DOM 元素作为模板:
<div id="app">
<p>{{ message }}</p>
</div>
<script>
new Vue({
el: '#app',
data: {
message: 'Inline DOM template'
}
})
</script>
X-Template
通过 <script type="text/x-template"> 定义模板:
<script type="text/x-template" id="my-template">
<div>
<h2>{{ header }}</h2>
</div>
</script>
<script>
new Vue({
el: '#app',
template: '#my-template',
data: {
header: 'X-Template Example'
}
})
</script>
模板语法特性
插值
- 文本插值:
{{ }} - 原始 HTML:
v-html指令 - 属性绑定:
v-bind或:
指令
- 条件渲染:
v-if,v-else,v-show - 列表渲染:
v-for - 事件处理:
v-on或@ - 双向绑定:
v-model
计算属性和侦听器
computed: {
reversedMessage() {
return this.message.split('').reverse().join('')
}
},
watch: {
message(newVal, oldVal) {
console.log('Message changed')
}
}
模板编译过程
Vue 模板会经历以下编译步骤:

- 解析:将模板字符串转换为 AST(抽象语法树)
- 优化:标记静态节点以便后续重用
- 代码生成:将 AST 转换为渲染函数
运行时版本需要预编译模板,而完整版包含编译器可运行时编译模板。生产环境推荐使用预编译。






