組件之間的通信分為2種
<div id="app"></div> <script> // 子組件 Vue.component('Child',{ template:`<p>我是子組件,接收到父組件傳來的數(shù)據(jù):{{msg}}</p>`, //{{ }}使用數(shù)據(jù) props:['msg'] //在props中用msg屬性|變量來接收父組件傳來的數(shù)據(jù) }) // 父組件 Vue.component('Parent',{ template:` <div> <p>我是父組件</p> <child msg='hello'></child> <!--使用子組件。使用屬性向子組件傳遞數(shù)據(jù),子組件要用同名的變量來接收--> </div> ` }) new Vue({ el:'#app', template:`<parent></parent>` //使用父組件 }); </script>
如果要傳遞多個數(shù)據(jù),使用多個屬性即可。
<div id="app"></div> <script> // 子組件 Vue.component('Child',{ template:` <div> <p>我是子組件</p> <!-- @click='sendToParent',表示這個元素發(fā)生click事件時,就調(diào)用sendToParent()方法 --> <button @click='sendToParent'>發(fā)送數(shù)據(jù)給父組件</button> <!-- @事件,事件可以是預(yù)定義的,也可以是自定義的 --> </div>`, methods:{ sendToParent(){ this.$emit("received","hello"); //this.$emit("自定義的事件名",數(shù)據(jù)),表示當(dāng)前組件觸發(fā)指定事件,這個事件會攜帶指定的數(shù)據(jù) } } }) // 父組件 Vue.component('Parent',{ template:` <div> <p>我是父組件,這是子組件傳來的數(shù)據(jù):{{msg}}</p> <!--使用msg變量--> <!-- 使用子組件。發(fā)生received事件時,使用指定的方法來處理 --> <child @received="receivedFromChild"></child> </div> `, data(){ return{ msg:'' } }, methods:{ receivedFromChild(val){ //使用一個參數(shù)來接收數(shù)據(jù) this.msg=val; //將數(shù)據(jù)賦給data中的msg變量 } } }) new Vue({ el:'#app', template:`<parent></parent>` //使用父組件 }); </script>
@事件='',事件可以是預(yù)定義的,也可以是自定義的。
處理方式可以寫自定義函數(shù),比如 @click='send' ,也可以寫成 @click='send()' 。函數(shù)可以帶參數(shù),比如 @click='send("chy",1)' 。
處理方式也可以直接操作內(nèi)存中的變量,比如 @click='msg+=1' ,msg是內(nèi)存中的變量,能識別,
如果是 @click='alert(1)' 這種函數(shù),識別不了,報錯:alert() undefined
<div id="app"></div> <script> // 子組件 Vue.component('Child',{ template:` <div> <p>我是子組件</p> <!--發(fā)送時可以帶參數(shù)--> <button @click='sendToParent("chy",20)'>發(fā)送數(shù)據(jù)給父組件</button> </div>`, methods:{ sendToParent(val1,val2){ //對應(yīng)的函數(shù)自然要聲明參數(shù) this.$emit("received",val1,val2); //可以帶0個、1個、多個數(shù)據(jù),帶多個時逗號分隔即可。這些數(shù)據(jù)可以使用傳進(jìn)來的參數(shù)、表單字段的值等 } } }) // 父組件 Vue.component('Parent',{ template:` <div> <p>我是父組件,這是子組件傳來的數(shù)據(jù):{{msg1}} {{msg2}}</p> <!-- 注意:接收時不能帶參數(shù)表,帶參數(shù)表反而會出錯 --> <child @received="receivedFromChild"></child> </div> `, data(){ return{ msg1:'', msg2:'' } }, methods:{ receivedFromChild(val1,val2){ //傳來幾個數(shù)據(jù),就用幾個參數(shù)接收 this.msg1=val1; this.msg2=val2; } } }) new Vue({ el:'#app', template:`<parent></parent>` }); </script>