Vue 組件傳值幾種常用方法【總結(jié)】
使用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)站的支持!
相關(guān)文章
總結(jié)4個(gè)方面優(yōu)化Vue項(xiàng)目
在本篇文章里我們給大家整理了一篇關(guān)于優(yōu)化VUE項(xiàng)目的四個(gè)總要點(diǎn),對此有需要的朋友們學(xué)習(xí)下天。2019-02-02
VuePress在build打包時(shí)window?document?is?not?defined問題解決
這篇文章主要為大家介紹了VuePress在build打包時(shí)window?document?is?not?defined問題解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07
vue+Element實(shí)現(xiàn)搜索關(guān)鍵字高亮功能
這篇文章主要為大家詳細(xì)介紹了vue+Element實(shí)現(xiàn)搜索關(guān)鍵字高亮功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-05-05
Element中el-table動態(tài)合并單元格(span-method方法)
本文主要介紹了Element中el-table動態(tài)合并單元格(span-method方法),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05
Vue?export?default中的name屬性有哪些作用
這篇文章主要介紹了Vue?export?default中的name屬性有哪些作用,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03
Vue.js@2.6.10更新內(nèi)置錯誤處機(jī)制Fundebug同步支持相應(yīng)錯誤監(jiān)控
這篇文章主要介紹了Vue.js@2.6.10更新內(nèi)置錯誤處機(jī)制,F(xiàn)undebug同步支持相應(yīng)錯誤監(jiān)控 ,需要的朋友可以參考下2019-05-05

