vue組件之間傳值/調用方法的幾種方式


(一)父組件向子組件傳值==props

1.在父組件中使用子組件的地方綁定數據

<children :message="message"></children
 
2.子組件使用props接收父組件傳過來的數據
props:{
     message:String
}

3.示例:

粘貼圖片

粘貼圖片

 

(二)子組件向父組件傳值==$emit,也可以用來調用父組件中的方法

1.子組件直接使用$emit將內部數據傳遞給父組件

this.$emit("childByValue",this.childValue);
 
2.父組件中接收數據
 
<template>
     <child @childByVlaue="childByVlaue"></dhild>
</template>
 
methods:{
     childByValue:function(childValue){
          this.name=childValue;
     }
}

(三)可以通過$parent和$children獲取父子組件參數

$children[i].params

  

this.$parent.params

  

(四)兄弟之間傳值===Vuex

1.在state里定義數據和屬性

 
state: {
    userName: '',
  },

  

2.在mutation里定義函數

mutations: {
    setUserName(state, name) {
      state.userName = name
    },
},
 

3.設置值

this.$store.comit('setUserName',params)
 
4.獲取值
this.$store.state.user.userName
 

(五)父組件調用子組件的方法===ref

1.子組件的方法

methods:{
     childMethod(){
          alert("我是子組件的方法");
     }
}
 
2.父組件調用子組件的方法
<template>
     <child ref="child"></child>
     <div @click="parentMethod"></div>
</template>
methods:{
     parentMethod(){
          this.$refs.child.childMethod();
     }
}

(六)祖孫組件傳值provide/inject

父組件:

provide(){
	return {
		userInfo: this.userInfo
	}
}

 

子孫組件:

inject:["userInfo"],

 

 
 


免責聲明!

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



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