Skip to main content

Vue 2.x 插槽 slot 示例

· One min read
Alan

源文档

以下是 Vue 2.x 的 slot 语法:

Child.vue
<template>
<div>
<h1>这是子组件</h1>
<div>
<slot :person="person">
<span>这是默认插槽, age: {{person.age}}</span>
</slot>
</div>

<div>
<slot name="bottom" :personName="person.firstName + person.lastName" :fnGreet="greet">
<span>这是具名插槽, age: {{person.age}}</span>
</slot>
</div>
</div>
</template>
<script>
export default {
data() {
return {
person: {
firstName: "Alan",
lastName: "Wei",
age: 100
}
};
},
methods: {
greet() {
console.log(`Hello ${this.person.firstName}`);
}
}
}
<script>
Parent.vue
<template>
<div>
<h1>这是父组件组件</h1>
<Child>
<template v-slot:default="slotProps">
默认插槽: {{ slotProps.person.firstName }}
</template>

<template #bottom="{ personName, fnGreet }">
<button @click="fnGreet">打印</button>
</template>
</Child>
</div>
</template>
<script>
import Child from "./Child.vue";

export default {
components: { Child },
data() {
return {
city: { cityName: "北京" }
};
},
methods: {

}
}
<script>