Vue中v-slot插槽的使用
在vue2.6.0以上版本v-slot将取代slot-scope和slot。
这里取代的意思是:v-slot在调用时取代了 slot 和 slot-scope,而在template中声明时仍会用solt进行声明插槽。
- 匿名插槽
<!-- 1.匿名插槽 -->
<div id="app1">
<cpn1>
<template v-slot>
</template>
</cpn1>
</div>
<script>
Vue.component('cpn1', {
template: `
<h1><slot>我是匿名插槽</slot></h1>
`
})
const app = new Vue({
el: "#app1"
})
2.具名插槽
<!-- 2.具名插槽 -->
<div id="app2">
<cpn2>
<template v-slot:header>
</template>
</cpn2>
</div>
<script>
Vue.component('cpn2', {
template: `
<h1><slot name="header">我是具名插槽</slot></h1>
`
})
const app2 = new Vue({
el: "#app2"
})
</script>
3.作用域插槽
<!-- 3.作用域插槽 -->
<div id="app3">
<cpn3>
<!-- default是指在编译时会去子级作用域中取当前子组件中的user属性 -->
<template v-slot:default="slotProps">
{{slotProps.user.name}}
</template>
</cpn3>
</div>
<script>
Vue.component('cpn3', {
template: `
<h1><slot v-bind:user="user">{{user.firstName}}</slot></h1>
`,
data() {
return {
user: {
name: "阿玮",
firstName: "郑"
}
}
}
})
const app3 = new Vue({
el: "#app3",
})
</script>
全部代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../js/vue.js"></script>
</head>
<body>
<!-- 1.匿名插槽 -->
<div id="app1">
<cpn1>
<template v-slot>
</template>
</cpn1>
</div>
<script>
Vue.component('cpn1', {
template: `
<h1><slot>我是匿名插槽</slot></h1>
`
})
const app = new Vue({
el: "#app1"
})
</script>
<!-- 2.具名插槽 -->
<div id="app2">
<cpn2>
<template v-slot:header>
</template>
</cpn2>
</div>
<script>
Vue.component('cpn2', {
template: `
<h1><slot name="header">我是具名插槽</slot></h1>
`
})
const app2 = new Vue({
el: "#app2"
})
</script>
<!-- 3.作用域插槽 -->
<div id="app3">
<cpn3>
<!-- default是指在编译时会去子级作用域中取当前子组件中的user属性 -->
<template v-slot:default="slotProps">
{{slotProps.user.name}}
</template>
</cpn3>
</div>
<script>
Vue.component('cpn3', {
template: `
<h1><slot v-bind:user="user">{{user.firstName}}</slot></h1>
`,
data() {
return {
user: {
name: "阿玮",
firstName: "郑"
}
}
}
})
const app3 = new Vue({
el: "#app3",
})
</script>
</body>
</html>