Vue之Componet之作用域slot
1.组件内有插槽,且插槽内有默认值,不用作用域插槽时,会按组件原样展示。完整代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="../js/vue.js"></script>
<title>slot02</title>
</head>
<body>
<!--实例-->
<div id="app">
<child></child>
</div>
<!--子组件template,且slot内有默认内容-->
<template id="childTemplate">
<slot>
<div>
{{firstName}}-{{lastName}}
</div>
</slot>
</template>
<script>
//定义子组件
Vue.component("child", {
template: "#childTemplate",
data() {
return {
firstName: "li",
lastName: "san"
}
}
})
//root
new Vue({
el: "#app"
})
</script>
</body>
</html>
运行结果:
如果想改变插槽原来显示样式就要用到作用域插槽。更改代码:
在子组件的模板里自定义属性用来绑定数据。
<!--子组件template,且slot内有默认内容-->
<template id="childTemplate">
<slot :fn="firstName" :ln="lastName">
<div>
{{firstName}}-{{lastName}}
</div>
</slot>
</template>
在父组件模板里,用v-slot=“name” 来接收子组件的数据。名字自定义。
<div id="app">
<child>
<template v-slot="name">
<div>
<span>your firstName is :{{name.fn}}</span>
<span>your lastName is :{{name.ln}}</span>
</div>
</template>
</child>
</div>
运行结果:
总结:
1.在子组件的模板里自定义属性用来绑定数据。
2.在父组件模板里,用v-slot=“name” 来接收子组件的数据。名字自定义。
3.如果是具名插槽,s-slot:插槽名=自定义变量。