slot 插槽 在父组件中引用的子组件 在父组件中写入百度 可在子组件slot插槽中展示出
父组件
<template>
<div id="app">
<child url="https://www.baidu.com">百度child>
div>
template>
<script>
import child from "./components/child.vue";
export default {
name: "App",
components: {
child,
},
};
script>
<style>
style>
子组件
<template>
<div class="child">
<a :href="url">
<slot>slot>
a>
div>
template>
<script>
export default {
name: "nav_child",
props: ["url"],
};
script>
父组件
<template>
<div id="app">
<child url="https://www.baidu.com">百度---{{ user.name }}child>
div>
template>
<script>
import child from "./components/child.vue";
export default {
name: "App",
components: {
child,
},
data() {
return {
user: {
name: "作用域",
},
};
},
};
script>
<style>
style>
子组件
<template>
<div class="child">
<a :href="url">
<slot>slot>
a>
div>
template>
<script>
export default {
name: "nav_child",
props: ["url"],
};
script>
这里父组件可以访问父组件的数据并且可在slot中展示到,不可以在父组件中访问子组件的数据,就相当于父组件百度—{{ user.name }}{{ url }}
这里的url是访问不到的 会报错,想拿到子组件的数据请看下面的代码
父组件
<template>
<div id="app">
<child>
<template v-slot:header>
<h1>header是标题h1>
div>
<template>
<p>这是一段内容在匿名插槽中显示p>
template>
<template v-slot:footer>
<p>footer是底部p>
template>
child>
div>
template>
<script>
import child from "./components/child.vue";
export default {
name: "App",
components: {
child,
},
data() {
return {
};
},
};
script>
<style>
style>
子组件
<template>
<div class="child">
<header>
<slot name="header">slot>
header>
<main>
<slot>slot>
main>
<footer>
<slot name="footer">slot>
footer>
div>
template>
<script>
export default {
name: "nav_child",
};
script>
父组件
<template>
<div id="app">
<child url="https://www.baidu.com" v-slot="slotProp"
>百度---{{ user.name }}地址为{{ slotProp.url }}child
>
div>
template>
<script>
import child from "./components/child.vue";
export default {
name: "App",
components: {
child,
},
data() {
return {
user: {
name: "作用域",
},
};
},
};
script>
<style>
style>
子组件
<template>
<div class="child">
<a :href="url">
<slot :url="url">slot>
a>
div>
template>
<script>
export default {
name: "nav_child",
props: ["url"],
};
script>