vue实现模板功能
Vue 实现模板功能的方法
Vue.js 提供了多种方式来实现模板功能,包括使用插槽(Slots)、动态组件(Dynamic Components)以及渲染函数(Render Functions)。以下是几种常见的实现方法:
使用插槽(Slots)
插槽是 Vue 中实现内容分发的重要机制,允许父组件向子组件传递模板内容。
<!-- 子组件 -->
<template>
<div>
<h2>子组件标题</h2>
<slot></slot>
</div>
</template>
<!-- 父组件 -->
<template>
<ChildComponent>
<p>这是父组件传递的内容</p>
</ChildComponent>
</template>
具名插槽可以更灵活地分发内容:
<!-- 子组件 -->
<template>
<div>
<slot name="header"></slot>
<slot></slot>
<slot name="footer"></slot>
</div>
</template>
<!-- 父组件 -->
<template>
<ChildComponent>
<template v-slot:header>
<h1>头部内容</h1>
</template>
<p>默认内容</p>
<template v-slot:footer>
<p>底部内容</p>
</template>
</ChildComponent>
</template>
动态组件
动态组件允许根据条件切换不同的组件模板。
<template>
<component :is="currentComponent"></component>
</template>
<script>
export default {
data() {
return {
currentComponent: 'ComponentA'
}
}
}
</script>
渲染函数
对于更复杂的模板逻辑,可以使用渲染函数直接操作虚拟 DOM。
export default {
render(h) {
return h('div', [
h('h1', '标题'),
this.$slots.default
])
}
}
作用域插槽
作用域插槽允许子组件向父组件传递数据。
<!-- 子组件 -->
<template>
<div>
<slot :user="user"></slot>
</div>
</template>
<script>
export default {
data() {
return {
user: { name: '张三' }
}
}
}
</script>
<!-- 父组件 -->
<template>
<ChildComponent>
<template v-slot:default="slotProps">
<p>{{ slotProps.user.name }}</p>
</template>
</ChildComponent>
</template>
动态模板
通过 v-html 指令可以动态渲染 HTML 字符串。
<template>
<div v-html="dynamicTemplate"></div>
</template>
<script>
export default {
data() {
return {
dynamicTemplate: '<p>动态内容</p>'
}
}
}
</script>
函数式组件
函数式组件是无状态的组件,适合纯展示用途。
export default {
functional: true,
render(h, { props }) {
return h('div', props.content)
}
}
以上方法可以根据具体需求选择使用,灵活组合以实现复杂的模板功能。







