vue模版实现
以下是Vue模板实现的常见方法和示例,分为基础语法、数据绑定、条件渲染、列表渲染等部分:
基础模板结构
Vue单文件组件(.vue)通常包含<template>、<script>和<style>三个部分:
<template>
<div id="app">
{{ message }}
</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello Vue!'
}
}
}
</script>
<style scoped>
#app {
font-size: 16px;
}
</style>
数据绑定
使用双大括号插值或v-bind指令:
<template>
<div>
<p>{{ dynamicText }}</p>
<a v-bind:href="url">Link</a>
<!-- 简写 -->
<a :href="url">Shortcut</a>
</div>
</template>
条件渲染
v-if和v-show控制元素显示:

<template>
<div>
<p v-if="isVisible">显示内容</p>
<p v-else>备选内容</p>
<span v-show="hasError">错误提示</span>
</div>
</template>
列表渲染
v-for渲染数组或对象:
<template>
<ul>
<li v-for="(item, index) in items" :key="item.id">
{{ index }} - {{ item.name }}
</li>
</ul>
</template>
事件处理
v-on监听DOM事件:
<template>
<button v-on:click="handleClick">Click</button>
<!-- 简写 -->
<button @click="handleClick">Shortcut</button>
</template>
表单输入绑定
v-model实现双向绑定:

<template>
<input v-model="inputText" placeholder="Edit me">
<p>Message is: {{ inputText }}</p>
</template>
插槽使用
父组件传递模板片段:
<!-- 子组件 -->
<template>
<div class="container">
<slot name="header"></slot>
<slot></slot>
</div>
</template>
<!-- 父组件 -->
<template>
<ChildComponent>
<template v-slot:header>
<h1>标题</h1>
</template>
<p>默认插槽内容</p>
</ChildComponent>
</template>
动态组件
通过is属性切换组件:
<template>
<component :is="currentComponent"></component>
</template>
自定义指令
注册并使用自定义指令:
<template>
<p v-highlight="'yellow'">高亮文本</p>
</template>
<script>
export default {
directives: {
highlight(el, binding) {
el.style.backgroundColor = binding.value
}
}
}
</script>
这些示例覆盖了Vue模板的核心功能,实际开发中可根据需求组合使用这些特性。注意模板中避免使用纯JavaScript表达式,复杂逻辑应移至计算属性或方法中处理。






