• 首页 Home
  • 简介 About
  • 项目 Service
  • 案例 Cases
  • 新闻 News
  • 技术文章 本硕新闻 行业资讯

    [vue]子组件通过$emit调用父组件的方法以及传递数据给父组件

    发表时间:2019-05-10  热度:

    原理也很简单,子组件使用$emit来触发父组件的函数,子组件借助这个父组件的函数将数据传给父组件。

    父组件中方法:

    <template>
    <div>{{ChildData}}</div>
    <router-view @pushData="getChildData"></router-view>
    </template>
    <script>
    export default {
    data:function(){
    return{
    ChildData:"",//定义获取子组件的数据
    }
    },
    methods:{
    getChildData (data) {
    this.ChildData=data//想要获取子组件的数据,并赋值给自己的ChildData
    }
    }
    }
    </script>

     

    子组件的数据,并且调用父组件函数来传值:

    <template>
    <div @click="sendYourData">点我将数据传给父组件</div>
    </template>
    <script>
    export default {
    data:function(){
    return{
    YourData:"我是来自子组件的数据呢",
    }
    },
    methods:{
    sendYourData:function () {
    this.$emit('pushData',this.YourData)
    }
    }
    }
    </script>

     

    文章怎么样?
    相关资讯