一个故事讲懂vue父子组件传值

讲故事前先讲代码

父组件向子组件传值

父组件数据传递给子组件可以通过props属性来实现
父组件:

<template>
  <div id="app">
    <child-component v-bind:dataOfChild="dataOfParent"></child-component>
  </div>
</template>

<script>
  import childComponent from './components/childComponent'

  export default {
    name: 'App',
    data(){
      return {
        dataOfParent:'1111111111'
      }
    },
    components:{
      childComponent
    },
  }
</script>

子组件:

<script>
export default {
  name: 'childComponent',
  //子组件通过props来接收数据:
  props:['dataOfChild'],
  data () {
    return {
      dataOfChild:this.dataOfChild
    }
  }
}
</script>

父向子传值总结:

v-bind:dataOfChild="dataOfParent"(父组件)====>props:['dataOfChild'](子组件)

子组件向父组件传值

子组件:

<template>
  <div>
    <button @click="sendDataToParent">向父组件传值</button>
  </div>
</template>

<script>
  export default {
    name: 'childComponent',
    methods:{
      sendDataToParent:function () {
        //$emit(even,value)even 是一个函数,value 是传给父组件的值
        this.$emit('parentFunction','helloworld')
      },
    }
  }
</script>

父组件:

<template>
  <div id="app">
    <!--监听子组件触发的parentFunction事件,然后调用customParentFunction方法-->
    <child-component v-on:parentFunction="customParentFunction"></child-component>
  </div>
</template>

<script>
  import childComponent from './components/childComponent'

  export default {
    name: 'App',
    components:{
      childComponent
    },
    methods: {
      customParentFunction:function (data) {
        console.log('子组件传过来的值',data)
        //helloworld
      }
    }
  }
</script>

子向父传值总结:

this.$emit('parentFunction','helloworld')(子组件)====>
v-on:parentFunction="customParentFunction"(父组件)====>
customParentFunction:function (data) {}(父组件)
接下来是强化记忆阶段:

《一个故事讲懂vue父子组件传值》

情节一

话说,在遥远的大山那边,有一对父子,父亲叫老王,儿子叫小明。父亲由于岁数大了,平常就在家干点农活,小明为了养家,外出打工。
有一天,小明想爸爸了,拿起手机给爸爸发短信,子组件主动向父组件传值,小明拿起手机,调用sendDataToParent方法,在通讯录找到了爸爸的手机号,this.$emit的第一个参数,函数名,然后拿起手机,抠了一堆字:爸爸我想你了,最近怎么样?this.$emit的第二个参数,内容,然后发送~,短信传到了信号塔,child-component相当于基站,基站对所有短信进行监听,正好,基站的列表里有小明父亲的名单,===》v-on:parentFunction,然后,短信又由基站传到了老王那边,老王的手机铃想了:苍茫的天涯是我的爱 绵绵的青山脚下花正开~~~响铃相当于调用customParentFunction方法,然后,值就传过来了

情节二

但是呢,小明在外打工,有时工作比较忙,忘了给爸爸发短信,所以老王想儿子了,但老王比较保守,又没大上过学,也不会打字,所以写了封信,去了邮局。

《一个故事讲懂vue父子组件传值》

老王用笔在纸上写了好多内容,把纸
纸相当于dataOfParent,也就是数据 放进了信封
信封相当于属性,也就是v-bind:dataOfChild里,然后给了邮局
相当于child-component,相当于一个中介,快递员进行派送,小明来到邮箱
相当于props,看到里边有封信
相当于父组件的值,拿了出来。

本文是作者第一次用情景故事的形式来写博客,也是一次新的尝试,如有不足,或者错的地方,还请大家多多指点。

    原文作者:李佳明先生
    原文地址: https://www.jianshu.com/p/2272b6ca0f0c
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞