插槽【vue2】与【vue3】对比
- Vue.js
- 13天前
- 14热度
- 0评论
插槽在Vue2和Vue3中的对比
插槽是Vue框架中用于实现组件间通信的重要机制之一。本文将详细介绍默认插槽、具名插槽以及作用域插槽在Vue2和Vue3版本之间的差异,帮助开发者更好地理解和使用插槽。
默认插槽
Vue2默认插槽
子组件:
<div class="layout-container">
<slot>普通插槽,默认内容</slot>
</div>父组件:
<layout>
<template v-slot:default>默认插槽传递内容: default</template>
</layout>Vue2中,如果不需要使用具名或作用域插槽,则可以省略v-slot:default指令。
<layout>
默认插槽传递内容: default
</layout>从2.6版本开始,引入了v-slot(缩写为#)用于替代旧的slot和slot-scope语法。
Vue3默认插槽
Vue3中使用与Vue2相同的标准语法:
<template>
<div>
<layout>
默认插槽传递内容: default
</layout>
</div>
</template>
具名插槽
Vue2具名插槽
子组件:
<div class="layout-container">
<header style="background-color: green">
<slot name="header">具名插槽header,默认内容</slot>
</header>
<main style="background-color: yellow">
<slot name="main">具名插槽main,默认内容</slot>
</main>
<footer style="background-color: yellowgreen">
<slot name="footer">具名插槽footer,默认内容</slot>
</footer>
</div>父组件:
<layout>
<template v-slot:header>默认插槽传递内容: header</template>
<template v-slot:main>默认插槽传递内容: main</template>
<template v-slot:footer>默认插槽传递内容: footer</template>
</layout>Vue3具名插槽
在Vue3中,如果父组件只需要使用一个具名插槽且不涉及作用域数据时,可以省略<template>标签:
<ChildComponent #header>
<h2>这是头部内容</h2>
</ChildComponent>作用域插槽
Vue2作用域插槽
子组件:
<div class="layout-container">
<slot :hobby="hobby">默认插槽的默认内容</slot>
</div>
<script>
export default {
name: 'layout',
data() {
return {
hobby: ['吃饭', '睡觉'],
};
},
};
</script>父组件:
<template v-slot:default="props">
<h2 v-for="item in props.hobby" :key="item">{{ item }}</h2>
</template>
<script>
export default {
components: {
Layout,
},
};
</script>Vue3作用域插槽
Vue3中使用v-slot与Vue2一致:
<ChildComponent #default="{ hobby }">
<div v-for="item in hobby" :key="item">{{ item }}</div>
</ChildComponent>具名和作用域插槽结合
Vue2具名和作用域插槽
子组件:
<div class="layout-container">
<slot name="header" :hobby="hobby"></slot>
<slot name="main" :hobby="hobby"></slot>
<slot name="footer" :hobby="hobby"></slot>
</div>
<script>
export default {
data() {
return {
hobby: ['吃饭', '睡觉'],
};
},
};
</script>父组件:
<layout>
<template #header="{ hobby }">
<h2 v-for="item in hobby" :key="item">{{ item }}</h2>
</template>
<template #main="{ hobby }">
<h2 v-for="item in hobby" :key="item">{{ item }}</h2>
</template>
<template #footer="{ hobby }">
<h2 v-for="item in hobby" :key="item">{{ item }}</h2>
</template>
</layout>动态插槽名
Vue3动态插槽
Vue3引入了对动态插槽的支持,允许使用JavaScript表达式作为插槽名称:
<ChildComponent>
<template #[dynamicSlotName]>
<p>这是动态插槽内容</p>
</template>
</ChildComponent>
<script setup>
import { ref } from 'vue';
const dynamicSlotName = ref('header');
</script>总结
通过本文的介绍,可以清晰地看到Vue3在插槽机制上的改进和增强。特别是在动态插槽名的支持上,使得组件编写更加灵活便捷。
以上就是关于插槽在Vue2和Vue3中的对比分析,希望对你有所帮助。