vue父子组件slot插槽的使用

Raissa ·
更新时间:2024-09-20
· 398 次阅读

目录

vue父子组件slot插槽

1.创建一个子组件并在vue实例中注册

2.在HTML代码中使用子组件

3.在vue实例中写入想要插入到子组件的内容

4.在子组件的模板中通过一个slot标签

vue插槽v-slot实现父向子传值

vue父子组件slot插槽

关于父组件在使用子组件的时候,向子组件插入内容的方法

1.创建一个子组件并在vue实例中注册

这是创建子组件

var testzujian = {         template:`<div>             <span>这是子组件的内容</span>                </div>`     }

这是注册子组件

let vm = new Vue({     el:'.root',      components:{             testzujian:testzujian         }, }) 2.在HTML代码中使用子组件 <body>     <div class="root">         <testzujian></testzujian>         </div> </body> 3.在vue实例中写入想要插入到子组件的内容 let vm = new Vue({         el:'.root',         components:{             testzujian:testzujian         },         template:`<div>             <testzujian>                 <template v-slot:slotcontent>                     <span>这是父组件向子组件插入的内容</span>                     </template>              </testzujian>             </div>`,     })

其中template是一个模板字符串,这个模板字符串里面最外面的div标签是根目录,必须存在。

根目录之下的是已经注册的子组件,也是需要加内容的子组件标签,必须存在

子组件标签之内的也是必须存在的

其上的属性v-slot绑定了一个名字slotcontent,这个名字可以随意取,但必须得有

这个标签里面就用来添加

父组件想要插入子组件的内容

4.在子组件的模板中通过一个slot标签

来引入父组件模板中内添加的内容

var testzujian = {         template:`<div>             <span>这是子组件的内容</span>             <slot name="slotcontent">             </slot>                 </div>`     }

这是刚才创建好的子组件,现在在其template的模板中,加入了一个slot标签,属性name绑定为刚才中v-slot:绑定的名字,也就是slotcontent

vue插槽v-slot实现父向子传值 // 子组件代码 <template> <div class="child"> <h4>this is child component</h4> <p>收到来自父组件的消息: <slot name="child"></slot> <!--展示父组件通过插槽传递的{{message}}--> </p> </div> </template> //父组件代码 <template> <div class="parent"> <h3>this is parent component</h3> <input type="text" v-model="message" /> <Child> <template v-slot:child> {{ message }} <!--插槽要展示的内容--> </template> </Child> </div> </template> <script> import Child from './child' export default { name: 'Parent', data() { return { message: '内容', } }, components: { Child, }, } </script>

以上为个人经验,希望能给大家一个参考,也希望大家多多支持软件开发网。 



VUE slot

需要 登录 后方可回复, 如果你还没有账号请 注册新账号