使用vue也有很多年了,一直都沒有整理一下相關(guān)知識,給大家總結(jié)下開發(fā)過程中所遇到的一些坑,主要給大家總結(jié)一下vue組件傳值的幾種常用方法:
1、通過路由帶參數(shù)傳值
① A組件通過query把id傳給B組件
this.$router.push({path:'/B',query:{id:1}})
② B組件接收
this.$route.query.id
2、父組件向子組件傳值
使用props向子組件傳遞數(shù)據(jù)
子組件部分:child.vue
<template> <div> <ul> <li v-for='(item,index) in nameList' :key='index'>{{item.name}}</li> </ul> </div> </template> <script> export default { props:['nameList'] } </script>
父組件部分:
<template> <div> <div>這是父組件</div> <child :name-list='names'></child> </div> </template> <script> import child from './child.vue' export default { components:{ child }, data(){ return{ names:[ {name:'柯南'}, {name:'小蘭'}, {name:'工藤新一'} ] } } } </script>
3、子組件向父組件傳值
子組件主要通過事件向父組件傳遞數(shù)據(jù):
子組件部分:
<template> <div> <ul> <li v-for='(item,index) in nameList' :key='index'>{{item.name}}</li> </ul> <Button @click='toParent'>點(diǎn)擊我</Button> </div> </template> <script> export default { props:['nameList'], methods:{ toParent(){ this.$emit('emitData',123) } } } </script>
父組件部分:
<template> <div> <div>這是父組件</div> <child :name-list='names' @emitData='getData'></child> </div> </template> <script> import child from './child.vue' export default { components:{ child }, data(){ return{ names:[ {name:'柯南'}, {name:'小蘭'}, {name:'工藤新一'} ] } }, methods:{ getData(data){ console.log(data); //123 } } } </script>
總結(jié)
以上所述是小編給大家介紹的Vue 組件傳值幾種常用方法【總結(jié)】,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時(shí)回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com