vue实现模板
Vue 模板实现方法
Vue.js 提供了多种方式实现模板功能,以下是常见的几种方法:
单文件组件 (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() {
console.log('Button clicked')
}
}
}
</script>
<style scoped>
h1 {
color: #42b983;
}
</style>
字符串模板 直接在组件选项中定义模板字符串:
new Vue({
template: `
<div>
<p>{{ message }}</p>
</div>
`,
data() {
return {
message: 'Hello Vue!'
}
}
})
DOM 内联模板 在 HTML 中直接编写模板:
<div id="app">
<template id="my-template">
<span>{{ counter }}</span>
<button @click="increment">+1</button>
</template>
</div>
<script>
new Vue({
el: '#app',
template: '#my-template',
data: {
counter: 0
},
methods: {
increment() {
this.counter++
}
}
})
</script>
渲染函数 使用 JavaScript 的渲染函数创建虚拟 DOM:
new Vue({
el: '#app',
render(h) {
return h('div', [
h('h1', 'Rendered Title'),
h('button', {
on: {
click: this.handleClick
}
}, 'Render Button')
])
},
methods: {
handleClick() {
alert('Button clicked')
}
}
})
模板语法特性
插值
<template>
<span>Message: {{ msg }}</span>
</template>
指令
<template>
<p v-if="show">Conditional rendering</p>
<a v-bind:href="url">Bound attribute</a>
<button v-on:click="doSomething">Event binding</button>
</template>
计算属性
computed: {
reversedMessage() {
return this.message.split('').reverse().join('')
}
}
条件渲染
<template>
<div v-if="type === 'A'">Type A</div>
<div v-else-if="type === 'B'">Type B</div>
<div v-else>Other Type</div>
</template>
列表渲染
<template>
<ul>
<li v-for="(item, index) in items" :key="item.id">
{{ index }} - {{ item.text }}
</li>
</ul>
</template>
模板最佳实践
为列表项设置唯一的 key 属性提高渲染性能
避免在模板中使用复杂逻辑,将复杂计算移至计算属性
合理使用 v-if 和 v-show:
v-if是真正的条件渲染,会销毁和重建元素v-show只是切换 CSS 的display属性
对于频繁切换的元素使用 v-show,运行时条件变化少的用 v-if
使用 v-bind 和 v-on 的缩写形式:

<template>
<a :href="url">Link</a>
<button @click="submit">Submit</button>
</template>






