vue slot與傳參實(shí)例代碼講解
插槽分為默認(rèn)插槽和具名插槽:
默認(rèn)插槽:
//父組件 <div> <h3>父組件</h3> <testChild> <div>默認(rèn)插槽</div> </testChild> </div> //子組件 <div> <h4>子組件</h4> <slot></slot> </div>
具名插槽:
注意:具名插槽需要包裹在 template 標(biāo)簽中,否則會(huì)報(bào)錯(cuò)
//父組件 <div> <h3>父組件</h3> <testChild> <template v-slot:test>//v-slot: + 插槽名 <ul> <li v-for="item in list">{{item.name}}</li> </ul> </template> </testChild> </div> //子組件 <div> <h4>子組件</h4> <slot name="test"></slot> //name="插槽名" </div>
子組件向父組件傳參:
//父組件 <div> <h3>父組件</h3> <testChild> <template v-slot:test="data">//具名插槽,v-slot: +插槽名+ ="自定義數(shù)據(jù)名",子組件所傳參數(shù)都是其屬性 <ul> <li v-for="item in data.list2">{{item.name}}</li> </ul> </template> <template v-slot="dataDefalut">//默認(rèn)插槽 {{dataDefalut.sName}} </template> </testChild> </div> //子組件 <template> <div> <h4>子組件</h4> <slot name="test" :list2="list2"></slot> <slot :sName="name"></slot> </div> </template> <script> export default { name: "testChild", data(){ return { list2:[ {name:'ccc'}, {name:'ddd'} ], name:'name' } } } </script>
結(jié)果:
補(bǔ)充:vue 利用slot向父組件傳值
閑話不多說(shuō),上代碼
子組件,里面有slot插槽,并在slot上綁定了text值
<template> <div @click="$emit('change',checked+1)"> <slot name="icon" :text="text"></slot> </div> </template> <script> export default{ data(){ return { text:"我是子組件" } }, props:["checked"], model:{ prop: 'checked', event: 'change' } } </script>
父組件通過(guò)slot-scope就可以拿到子組件slot上綁定的值,并且2.5.0版本可以用于任意元素上
<template> <div id="app"> <img src="./assets/logo.png"> <!--<router-view/>--> <car v-model="index"> <div slot="icon" slot-scope="props"> {{props.text}} </div> </car> </div> </template>
這樣,就可以拿到子組件里面的text值。
總結(jié)
以上所述是小編給大家介紹的vue slot與傳參實(shí)例代碼講解,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的!
相關(guān)文章
vue3中配置文件vue.config.js不生效的解決辦法
這篇文章主要介紹了vue3中配置文件vue.config.js不生效的解決辦法,文中通過(guò)代碼示例講解的非常詳細(xì),對(duì)大家解決問(wèn)題有一定的幫助,需要的朋友可以參考下2024-05-05Vue3+Spring Framework框架開(kāi)發(fā)實(shí)戰(zhàn)
這篇文章主要為大家介紹了Vue3+Spring Framework框架開(kāi)發(fā)實(shí)戰(zhàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04vue+iview如何實(shí)現(xiàn)拼音、首字母、漢字模糊搜索
這篇文章主要介紹了vue+iview如何實(shí)現(xiàn)拼音、首字母、漢字模糊搜索,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04vue-cli2 構(gòu)建速度優(yōu)化的實(shí)現(xiàn)方法
這篇文章主要介紹了vue-cli2 構(gòu)建速度優(yōu)化的實(shí)現(xiàn)方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-01-01Vue中的v-for循環(huán)key屬性注意事項(xiàng)小結(jié)
這篇文章主要介紹了Vue中的v-for循環(huán)key屬性注意事項(xiàng)小結(jié),非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-08-08vue如何通過(guò)插槽組件之間數(shù)據(jù)傳遞
這篇文章主要介紹了vue如何通過(guò)插槽組件之間數(shù)據(jù)傳遞問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06Vue?2源碼解析ParseHTML函數(shù)HTML模板
這篇文章主要為大家介紹了Vue?2源碼解析ParseHTML函數(shù)HTML模板詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08