轉載
原文地址:https://blog.csdn.net/liyunkun888/article/details/83269692
前言
vue的組件傳值分為三種方式:父傳子、子傳父、非父子組件傳值
引用官網的一句話:父子組件的關系可以總結為 prop 向下傳遞,事件向上傳遞
父組件通過 prop 給子組件下發數據,子組件通過事件給父組件發送消息,如下圖所示:
下面我們就開始用代碼(一言不合就上代碼)詳細的介紹vue組件傳值的三種方式
1、父傳子
子組件的代碼:
<template> <div id="container"> {{msg}} </div> </template> <script> export default { data() { return {}; }, props:{ msg: String } }; </script> <style scoped> #container{ color: red; margin-top: 50px; } </style>
父組件的代碼:
<template> <div id="container"> <input type="text" v-model="text" @change="dataChange"> <Child :msg="text"></Child> </div> </template> <script> import Child from "@/components/Child"; export default { data() { return { text: "父組件的值" }; }, methods: { dataChange(data){ this.msg = data } }, components: { Child } }; </script> <style scoped> </style>
父傳子的實現方式就是通過props屬性,子組件通過props屬性接收從父組件傳過來的值,而父組件傳值的時候使用 v-bind 將子組件中預留的變量名綁定為data里面的數據即可
2、子傳父
子組件代碼:
<template> <div id="container"> <input type="text" v-model="msg"> <button @click="setData">傳遞到父組件</button> </div> </template> <script> export default { data() { return { msg: "傳遞給父組件的值" }; }, methods: { setData() { this.$emit("getData", this.msg); } } }; </script> <style scoped> #container { color: red; margin-top: 50px; } </style>
父組件代碼:
<template> <div id="container"> <Child @getData="getData"></Child> <p>{{msg}}</p> </div> </template> <script> import Child from "@/components/Child"; export default { data() { return { msg: "父組件默認值" }; }, methods: { getData(data) { this.msg = data; } }, components: { Child } }; </script> <style scoped> </style>
子傳父的實現方式就是用了 this.$emit 來遍歷 getData 事件,首先用按鈕來觸發 setData 事件,在 setData 中 用 this.$emit 來遍歷 getData 事件,最后返回 this.msg
總結:
子組件中需要以某種方式例如點擊事件的方法來觸發一個自定義事件
將需要傳的值作為$emit的第二個參數,該值將作為實參傳給響應自定義事件的方法
在父組件中注冊子組件並在子組件標簽上綁定對自定義事件的監聽
3、非父子
vue 中沒有直接子對子傳參的方法,建議將需要傳遞數據的子組件,都合並為一個組件
如果一定需要子對子傳參,可以先從傳到父組件,再傳到子組件(相當於一個公共bus文件)
為了便於開發,vue 推出了一個狀態管理工具 vuex,可以很方便實現組件之間的參數傳遞