目录
slot 具名插槽
what : 在子组件中定义插槽时,给对应的插槽分别起个名字,方便后边插入父组件将根据name来填充对应的内容
why : 为了让组件具备更强的通用性,不将自己暗中的内容限制为固定的div、span等元素,则可使用具名插槽
how : 插槽显不显示、怎样显示是由父组件来控制的,而插槽在哪里显示就由子组件来进行控制.
语法: <slot name = '名称'>默认值</slot>,
示例
在子组件 StuSlot.vue中定义两个具名插槽
<template> <div class="about"> <h1>This is a Children page</h1> <!-- 给插槽添加name属性,便成为具名插槽 --> <!-- 定义两个具名插槽--> <slot name="one"></slot> <slot name="two"></slot> </div> </template>
在父组件App.vue中:
为验证,子组件中的插槽可以填充任何结构的内容,所以专门在one插槽中插入一个组件,而在two插槽就单纯插入一串普通的数据
<template> <div id="about"> <h1>This is a Parent page</h1> <StuSlot> <template v-slot:one> <p>one 插槽</p> </template> <template v-slot:two> two插槽 </template> </StuSlot> </div> </template> <script> import StuSlot from './components/StuSlot.vue' export default { components:{ StuSlot } } </script> <style> </style>
效果
并且,子组件可以定义多个同名的具名插槽:
<template> <div class="about"> <h1>This is an Children page</h1> <!-- 给插槽加了个name属性,就是所谓的具名插槽了 --> <slot name="one"></slot> <slot name="two"></slot> <slot name="two"></slot> </div> </template>
props单向数据流
基本用法:
- 在父组件中的data中定义值
- 在子组件中使用props声明要引用哪个值
- 父组件的template中要在子组件标签上绑定
- 在template模板中,要使用中划线写法;在script脚本中使用小驼峰
基本应用场景:
- 静态props:静态即传入的值不变化,直接在父组件中定义,子组件中使用
- 动态props:动态即传入的值会变化,父组件中要动态地绑定父组件的数据
- props验证:验证传入的props参数的数据规格,如果不符合数据规格则发出警告,注意这个数据类型包含所有的数据类型,如基本类型和引用类型; 还可以在验证中加入自定义验证函数,当返回false时则发出警告
实例
Person.vue:
<template> <div class="props-container"> <h1>个人信息</h1> <h2>姓名:{{name}}</h2> <h2>性别:{{sex}}</h2> <h2>年龄:{{age}}</h2> <h2>我的兴趣爱好是:</h2> <ul> <li v-for="(item,index) in interest" :key="index">{{item}}</li> </ul> </div> </template> <script> export default { name:'', props:['name','age','sex','interest'] } </script> <style> .props-container { border: 1px solid orange; width: 300px; background-color: yellowgreen; padding: 10px; } h1, h2{ margin: 0; } </style>
App.vue
<template> <div id="about"> <!-- 使用组件 --> <Person :name="'胡图图'" :age="6" :sex="'男'" :interest="['羽毛球','吉他','桌球']"></Person> </div> </template> <script> // 导入组件 import Person from './components/person.vue' export default { // 注册组件 components:{ Person }, //传值 data(){ return{ name:"胡英俊" } } } </script>
效果