組件之間的通信分為2種
- 父子組件之間的通信
- 非父子組件之間的通信
父組件向子組件傳資料
<div id="app"></div> <script> // 子組件 Vue.component('Child',{ template:`<p>我是子組件,接收到父組件傳來的資料:{{msg}}</p>`, //{{ }}使用資料 props:['msg'] //在props中用msg屬性|變數來接收父組件傳來的資料 }) // 父組件 Vue.component('Parent',{ template:` <div> <p>我是父組件</p> <child msg='hello'></child> <!--使用子組件,使用屬性向子組件傳遞資料,子組件要用同名的變數來接收--> </div> ` }) new Vue({ el:'#app', template:`<parent></parent>` //使用父組件 }); </script>
如果要傳遞多個資料,使用多個屬性即可,
子組件向父組件傳資料
<div id="app"></div> <script> // 子組件 Vue.component('Child',{ template:` <div> <p>我是子組件</p> <!-- @click='sendToParent',表示這個元素發生click事件時,就呼叫sendToParent()方法 --> <button @click='sendToParent'>發送資料給父組件</button> <!-- @事件,事件可以是預定義的,也可以是自定義的 --> </div>`, methods:{ sendToParent(){ this.$emit("received","hello"); //this.$emit("自定義的事件名",資料),表示當前組件觸發指定事件,這個事件會攜帶指定的資料 } } }) // 父組件 Vue.component('Parent',{ template:` <div> <p>我是父組件,這是子組件傳來的資料:{{msg}}</p> <!--使用msg變數--> <!-- 使用子組件,發生received事件時,使用指定的方法來處理 --> <child @received="receivedFromChild"></child> </div> `, data(){ return{ msg:'' } }, methods:{ receivedFromChild(val){ //使用一個引數來接收資料 this.msg=val; //將資料賦給data中的msg變數 } } }) new Vue({ el:'#app', template:`<parent></parent>` //使用父組件 }); </script>
@事件='',事件可以是預定義的,也可以是自定義的,
處理方式可以寫自定義函式,比如 @click='send' ,也可以寫成 @click='send()' ,函式可以帶引數,比如 @click='send("chy",1)' ,
處理方式也可以直接操作記憶體中的變數,比如 @click='msg+=1' ,msg是記憶體中的變數,能識別,
如果是 @click='alert(1)' 這種函式,識別不了,報錯:alert() undefined
說明
<div id="app"></div> <script> // 子組件 Vue.component('Child',{ template:` <div> <p>我是子組件</p> <!--發送時可以帶引數--> <button @click='sendToParent("chy",20)'>發送資料給父組件</button> </div>`, methods:{ sendToParent(val1,val2){ //對應的函式自然要宣告引數 this.$emit("received",val1,val2); //可以帶0個、1個、多個資料,帶多個時逗號分隔即可,這些資料可以使用傳進來的引數、表單欄位的值等 } } }) // 父組件 Vue.component('Parent',{ template:` <div> <p>我是父組件,這是子組件傳來的資料:{{msg1}} {{msg2}}</p> <!-- 注意:接收時不能帶引數表,帶引數表反而會出錯 --> <child @received="receivedFromChild"></child> </div> `, data(){ return{ msg1:'', msg2:'' } }, methods:{ receivedFromChild(val1,val2){ //傳來幾個資料,就用幾個引數接收 this.msg1=val1; this.msg2=val2; } } }) new Vue({ el:'#app', template:`<parent></parent>` }); </script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/137182.html
標籤:JavaScript
上一篇:CSRF的幾種防御方法的利弊分析
