vue显示嵌套组件实现
嵌套组件的实现方法
在Vue中实现嵌套组件主要通过组件间的父子关系建立,以下是几种常见方式:
全局注册组件
通过Vue.component全局注册父组件和子组件,在父组件的模板中直接使用子组件标签:
Vue.component('parent-component', {
template: `
<div>
<child-component></child-component>
</div>
`
})
Vue.component('child-component', {
template: '<div>Child Component</div>'
})
局部注册组件
在父组件选项中通过components属性局部注册子组件:
const ChildComponent = {
template: '<div>Child Component</div>'
}
const ParentComponent = {
components: {
'child-component': ChildComponent
},
template: `
<div>
<child-component></child-component>
</div>
`
}
动态组件
使用<component>标签配合is属性实现动态嵌套:
const ComponentA = { template: '<div>Component A</div>' }
const ComponentB = { template: '<div>Component B</div>' }
new Vue({
data() {
return {
currentComponent: 'component-a'
}
},
components: {
'component-a': ComponentA,
'component-b': ComponentB
},
template: `
<div>
<component :is="currentComponent"></component>
</div>
`
})
插槽嵌套
通过插槽实现内容分发式嵌套:

const BaseLayout = {
template: `
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
</div>
`
}
new Vue({
components: { BaseLayout },
template: `
<base-layout>
<template v-slot:header>
<h1>Page Title</h1>
</template>
<p>Main content</p>
</base-layout>
`
})
递归组件
组件通过名称引用自身实现递归嵌套:
const TreeComponent = {
name: 'TreeComponent',
props: ['nodes'],
template: `
<ul>
<li v-for="node in nodes">
{{ node.name }}
<tree-component
v-if="node.children"
:nodes="node.children">
</tree-component>
</li>
</ul>
`
}
组件间通信方式
Props向下传递
父组件通过props向子组件传递数据:
Vue.component('child', {
props: ['message'],
template: '<span>{{ message }}</span>'
})
Vue.component('parent', {
template: '<child message="Hello from parent"></child>'
})
事件向上传递
子组件通过$emit触发父组件事件:

Vue.component('child', {
template: `
<button @click="$emit('custom-event', 'data')">
Click me
</button>
`
})
Vue.component('parent', {
methods: {
handleEvent(data) {
console.log(data) // 'data'
}
},
template: `
<child @custom-event="handleEvent"></child>
`
})
provide/inject
跨层级组件通信:
const Ancestor = {
provide() {
return {
sharedData: 'Shared value'
}
},
template: `<descendant></descendant>`
}
const Descendant = {
inject: ['sharedData'],
template: `<div>{{ sharedData }}</div>`
}
高级嵌套模式
渲染函数实现
使用渲染函数动态生成嵌套结构:
Vue.component('smart-list', {
props: ['items'],
render(h) {
return h('ul', this.items.map(item => {
return h('li', item.name)
}))
}
})
函数式组件
无状态组件的高效嵌套:
Vue.component('functional-item', {
functional: true,
props: ['item'],
render(h, context) {
return h('li', context.props.item.name)
}
})
这些方法可根据具体场景组合使用,实现从简单到复杂的各种组件嵌套需求。






