教程開始:
我們要實現的效果是:在子組件的Input框輸入,父組件中實時更新顯示。(也就是把子組件中的數據傳給父組件)
一、子組件代碼
template部分
<template> <section> <input v-model="message"/> </section> </template>
js部分
<script> export default { data(){ return { message:'請輸入' } }, //通過watch來監聽message是否改變 watch:{ 'message':function(){ this.$emit('getMessage',this.message);//主要是通過$emit方法來實現傳參的方式,第一個參數是自定義事件名稱,第二個則是要傳的數據 } } } </script>
其實不一定要用wacth來監聽數據變化,直接給input加個輸入事件,也是可以的。
二、父組件代碼
template部分
<template> <div id="app"> <!--getMessage是子組件那邊定義的 自定義事件--> <test @getMessage="getVal"></test> <div> 子組件輸入的值:{{chindVal}} </div> </div> </template>
js部分
<script> import test from './components/header' export default { data(){ return { chindVal:'', } }, components:{ test }, methods:{ getVal(msg){//msg就是傳過來的數據了 這只是個形參 名字可以隨意 this.chindVal=msg;//然后將數據賦值給chindVal } } } </script>
總結:
1.子組件傳參給父組件主要是通過$emit方法來實現的。
2.在子組件中使用$emit方法,一般它接受兩個參數,第一個是自定義事件(這個事件在父組件中需要用到),第二個參數就是需要傳的數據了。
3.而在父組件里,在調用的標簽上引用子組件定義的那個事件,然后事件綁定一個函數。在函數里面進行賦值即可。