這篇文章主要介紹了vue 父組件給子組件傳值,子組件給父組件傳值,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑑價值,需要的朋友可以參考下
父組件如何給子組件傳值
使用props
舉個例子:
子組件:fromTest.vue,父組件 app.vue
fromTest.vue
<template> <h2>{{title}}</h2> //title必須是父組件傳遞的 </template> <script> export default (){ props:["title"] //可以是數組,也可以是對象 //如何對title進行校驗 //props:{ // type:String,required:true //如果父組件不傳值就會報錯 //} } </script>
父組件 app.vue
<template> <from-test title = "你好 "></from-test> //1.指定值 //<from-test :title = "titleVar "></from-test> //2.動態傳值 titleVar 是變量 </template> <script> export default (){ data(){ titleVar :'你好' //動態傳值就代表數據這裏需要定義titleVar } } </script>
子組件如何給父組件傳值
事件,$emit
子組件
button.vue
<template> <button @click='handClick'></button> </template> <script> export default(){ methods(){ handClick(){ this.$emit(lalala,{message:"heihei"}) //lalala是函數名稱,後面是想要傳遞的值 } } } </script>
父組件
app.vue
<template> <k-button @lalala = handClick></k-button> </template> <script> import KButton form './components/KButton' //自己要記得導入組件,引用組件名稱 export default(){ components(){ KButton } methods(){ handClick(obj){ console.log(obj) //點擊button,控制檯就收到值了 } } } </script>
總結
以上所述是小編給大家介紹的vue 父組件給子組件傳值子組件給父組件傳值的實例代碼 ,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對神馬文庫網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請註明出處,謝謝!