Vue 父子組件之間的數據通訊--props,$emit

首先是父組件裏面的數據傳遞到子組件
這裏用props,props有支撐物的意思,能夠理解爲橋樑。props要寫在自組件裏面。vue

先定義一個子組件,在組件中註冊propsapp

<template>
    <div>
        <div>{{message}}(子組件)</div>
    </div>
</template>
<script>
export default {
    props: {
        message: String  //定義傳值的類型<br>    }
}
</script>
<style>
</style>

在父組件中,引入子組件,並傳入子組件內須要的值this

<template>
    <div>
        <div>父組件</div>
        <child :message="parentMsg"></child>  
    </div>
</template>
 
<script>
 
import child from './child'  //引入child組件
export default {
    data() {
            return {
                parentMsg: 'a message from parent'  //在data中定義須要傳入的值
            }
        },
        components: {
            child
        }
}
</script>
<style>
</style>

注:這種方式只能由父向子傳遞,子組件不能更新父組件內的datacode

接下來是子組件的數據傳遞到父組件
這裏用到了$emit ,emit有發射發出的意思,這就不難理解了component

tips: App.vue 父組件 / Hello.vue 子組件ip

父組件裏面的內容
<!--App.vue :-->input

<template>
  <div id="app">
    <hello @newNodeEvent="parentLisen" />
  </div>
</template>
<script>
 import hello from './components/Hello'
 export default {
  name: 'app',
  'components': {
   hello
  },
  methods: {
   parentLisen(evtValue) { 
    //evtValue 是子組件傳過來的值
    alert(evtValue)
   }
  }
 }
</script>

子組件裏面的內容
<!--Hello.vue :-->it

<template>
  <div class="hello">
    <input type="button" name="" id="" @click="chilCall()" value="子調父" /> 
  </div>
</template>
<script>
 export default {
  name: 'hello',
  'methods': {
   chilCall(pars) {
    this.$emit('newNodeEvent', '我是子元素傳過來的')
   }
  }
 }
</script>

$emit經過調用父的方法的方式完成了子向父的數據傳遞class

相關文章
相關標籤/搜索