网站建设与设计/免费网站服务器
目录
一、插槽
1、格式
2、内容
3、原理
二、具名插槽
1、定义
2、步骤
三、作用域插槽
1、使用前提
2、作用
3、步骤
四、子组件向父组件通信总结
1、三步骤
2、多参数传递例子
一、插槽
1、格式
放在子组件
<slot>内容</slot>
2、内容
可以放任何模块的代码
3、原理
父组件引用时,填写内容会被应用到插槽
css模块
<style>.box{width: 200px;height: 200px;background-color: aqua;float: left;margin-right: 20px;}
</style>
html模块
<body><div id="app"><cpn><a href="">点击</a></cpn><cpn><button>点击</button></cpn><cpn></cpn></div><template id="cpn"><div><div class="box"><h1>{{msg}}</h1><slot><h4>默认内容</h4></slot></div></div></template><script>new Vue({el:'#app',components:{cpn:{template:'#cpn',data(){return{msg:'子组件'}}}}})</script>
</body>
二、具名插槽
1、定义
使用多个插槽时,给slot添加name属性,设置slot名称
2、步骤
(1)<slot>标签添加绑定name属性
(2)便签显示处用<template>标签包裹,并绑定对应的slot,绑定方法如下:
①v-slot:插槽名【注意中间是英文冒号,不是等号】
②缩写:#插槽名
<body><div id="app"><cpn><template v-slot:slot1><div><a href="">跳转</a></div></template><template #slot2><div><a href="">点击</a></div></template></cpn><cpn><template #slot1><div><button>点击</button></div></template></cpn></div><template id="cpn"><div><div class="box"><slot name="slot1"></slot><h1>{{msg}}</h1><slot name="slot2"></slot></div></div></template><script>new Vue({el:'#app',components:{cpn:{template:'#cpn',data(){return{msg:'子组件'}}}}})</script>
</body>
三、作用域插槽
1、使用前提
要在具名插槽的基础上使用
2、作用
传递数据,将子组件的数据传递给父组件
3、步骤
(1)先设置好具名插槽
(2)在子组件的<slot>标签上自定义属性名来绑定参数
(3)在父组件的具名插槽上赋值形参接收传参
格式:#插槽名="形参"
<body><div id="app"><cpn><template #slot1="item"><div><h3>我是一个具名插槽</h3><h5>{{item}}</h5><h5>{{item.cityname}}</h5></div></template></cpn></div><template id="cpn"><div><h1>{{msg}}</h1><slot name="slot1" :cityName="city.name"><h4>默认内容</h4></slot></div></template><script>new Vue({el:'#app',components:{cpn:{template:'#cpn',data(){return{msg:'子组件',city:{name:'北京',},}},},},})</script>
</body>
四、子组件向父组件通信总结
1、三步骤
(1)子组件准备好需要传递的参数
自定义方法:this.$emit('自定义方法名',参数1,参数2...)
自定义方法名格式:采用复合型name-name
(2)连接标签:通过子组件与父组件的连接关键<cpn></cpn>
(3)父组件接收和存储子组件传递来的参数
2、多参数传递例子
<body><div id="app"><h4>{{idInfo}}</h4><h4>{{nameInfo}}</h4><h4>{{ageInfo}}</h4><detail @info-transfer="getInfo"></detail></div><template id="detail"><div><h1>{{msg}}</h1><button @click="btnClick">传递学生信息</button></div></template><script>new Vue({el:'#app',data:{idInfo:'未传递id',nameInfo:'未传递name',ageInfo:'未传递age',},methods:{getInfo(id,name,age){console.log(id,name,age);this.idInfo = idthis.nameInfo = namethis.ageInfo = age}},components:{detail:{template:'#detail',data(){return{msg:'测试',info:{id:'1',name:'申小兮',age:'18',}}},methods:{btnClick(){this.$emit('info-transfer',this.info.id,this.info.name,this.info.age)}}}}})</script>
</body>