在 Vue.js 中,当你想在一个插槽中使用数据时,例如:
<navigation-link url="/profile">
Logged in as {{ user.name }}
</navigation-link>该插槽跟模板的其它地方一样可以访问相同的 Vue 实例的属性 (也就是相同的 “作用域”),而不能访问 <navigation-link> 的作用域。例如 url 是访问不到的:
<navigation-link url="/profile">
Clicking here will send you to: {{ url }}
<!--
这里的 `url` 会是 undefined,因为其 (指该插槽的) 内容是
传递给 <navigation-link> 的而不是在 <navigation-link> 组件内部定义的。
-->
</navigation-link>注意:父级模板里的所有内容都是在父级作用域中编译的;子模板里的所有内容都是在子作用域中编译的。
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue</title>
<!-- 使用 CDN 引入 Vue 库 -->
<!-- <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> -->
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.7.9/vue.js"></script>
</head>
<body>
<div id="app">
<my-component title="Vue.js slot">
<!-- 从 vue 实例中获取数据 -->
{{ date }}
</my-component>
</div>
<script type="text/javascript">
Vue.component('sub-component', {
props: [ "summary" ],
template: `
<div style="background:red;">
<div>{{ summary }}</div>
</div>
`
});
Vue.component('my-component', {
props: [ "title" ],
template: `
<div style="background:yellow;">
<div>{{ title }}</div>
<!-- 引入子组件 -->
<sub-component summary="Hello Vue.js"></sub-component>
<slot></slot>
</div>
`
});
var app = new Vue({
el: "#app",
data: {
date: "DATE: 2023-06-21 13:08:56"
}
});
</script>
</body>
</html>运行效果图:
