1. 程式人生 > >vue 父子組件通信

vue 父子組件通信

span pla ret parent code () his ops hang

vue提倡單項數據流,因此在通常情況下都是父組件傳遞數據給子組件使用,子組件觸發父組件的事件,並傳遞給父組件所需要的參數。

props

上篇文章已經敘述過

$emit和$on

vm.$emit( event, arg ) //觸發當前實例上的事件

vm.$on( event, fn );//監聽event事件後運行 fn;

//父組件
<template>
  <div id="app">
    <v-child @pastInfo="sendMsg"></v-child>
  </div>
</template>

<script>
import Child from 
‘./components/Child‘ export default { components:{ ‘v-child‘:Child }, data(){ return{ parentMessage:‘來自父組件的信息‘ } }, methods:{ sendMsg(name,age){ console.log(this.parentMessage,name,age); } } } </script>
<template>
  <div>
    <div>子組件</div>
  </div>
</template>
<script>
export 
default { mounted(){ this.$emit(‘pastInfo‘,{name:‘zhangsan‘,age:‘10‘}) } } </script>

vue 父子組件通信