目录
放在子组件
<slot>内容slot>
可以放任何模块的代码
父组件引用时,填写内容会被应用到插槽
css模块
- .box{
- width: 200px;
- height: 200px;
- background-color: aqua;
- float: left;
- margin-right: 20px;
- }
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>

使用多个插槽时,给slot添加name属性,设置slot名称
(1)
(2)便签显示处用标签包裹,并绑定对应的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)在父组件的具名插槽上赋值形参接收传参
格式:#插槽名="形参"
- <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)子组件准备好需要传递的参数
自定义方法:this.$emit('自定义方法名',参数1,参数2...)
自定义方法名格式:采用复合型name-name
(2)连接标签:通过子组件与父组件的连接关键
(3)父组件接收和存储子组件传递来的参数
- <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 = id
- this.nameInfo = name
- this.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>


