vue 組件傳值 props $emit $event


父向子傳值

在父組件的data中定義要傳給子的屬性

1 export default {
2    data(){
3       return {
4          selectType:'radio'
5       }
6    }
7 }

 

父組件html調用子組件時綁定數據

<j-select-user-by-dep  :selectType="selectType"></j-select-user-by-dep>

 

子組件通過調用props獲取屬性(有倆種寫法,推薦第一種)

 1 export default {
 2   props:{
 3       selectType :{
 4         type:String, // 數據類型
 5         default: 'checkbox',// 默認值
 6         required: false//是否必須
 7       }
 8     }
 9   ....
10 }
1 export default {
2   props:['selectType']
3   ....
4 }

說明selectType為父調用組件綁定數據時,綁定屬性的名稱

子向父組件傳值

子組件使用$emit注冊事件

 

1 this.$emit("changeName","修改父name值");

 

 

 

父組件調用子組件時綁定事件,並使用$event獲取參數

 

1 <j-select-user-by-dep  @changeName="changeName($event)"></j-select-user-by-dep>

 

 

 

注意:參數名稱必須為$event

父組件事件

1 export default {
2   ....
3   methods:{
4       changeName:function(name){
5          this.name= name;
6       }
7   }
8   ....
9 }

說明:子向父組件傳值本質上為子調用父組件的函數,函數中獲取子組件傳入的值

傳值注意事項

傳值根據值的類型分為傳值(非對象類型)和傳引用(對象),傳引用時,傳的值在任意位置修改時,所有和當前對象綁定的內容均會發生變化。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM