Vue 組件傳值幾種常用方法【總結】
使用vue也有很多年了,一直都沒有整理一下相關知識,給大家總結下開發(fā)過程中所遇到的一些坑,主要給大家總結一下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'>點擊我</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>
總結
以上所述是小編給大家介紹的Vue 組件傳值幾種常用方法【總結】,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關文章
Vue中使用ElementUI使用第三方圖標庫iconfont的示例
這篇文章主要介紹了Vue中使用ElementUI使用第三方圖標庫iconfont的示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-10-10Vue中的函數(shù)同步執(zhí)行導致的數(shù)據(jù)獲取失敗問題處理辦法
Vue中的mount中有兩個函數(shù),第一個函數(shù)執(zhí)行完后給data中的userInfo賦值,但是第二個函數(shù)獲取userInfo時是空值,這種情況可能是因為第二個函數(shù)在獲取 userInfo 時發(fā)生在第一個函數(shù)執(zhí)行完之前,所以本文給大家介紹了Vue中的函數(shù)同步執(zhí)行導致的數(shù)據(jù)獲取失敗問題處理辦法2024-08-08vue?點擊按鈕?路由跳轉(zhuǎn)指定頁面的實現(xiàn)方式
這篇文章主要介紹了vue?點擊按鈕?路由跳轉(zhuǎn)指定頁面的實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04Vue-router不允許導航到當前位置(/path)錯誤原因以及修復方式
本文主要介紹了Vue-router不允許導航到當前位置(/path)錯誤原因以及修復方式,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09Vue 2.0+Vue-router構建一個簡單的單頁應用(附源碼)
這篇文章主要給大家介紹了基于Vue 2.0+Vue-router構建了一個簡單的單頁應用,文中通過實例介紹的非常詳細,并在文末給出了源碼下載,需要的朋友可以下載學習參考,下面來一起看看吧。2017-03-03