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

£神魔★判官ぃ 2022-10-26 11:29 292阅读 0赞

2019-05-10

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

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

父组件中方法:

  1. <template>
  2. <div>{
  3. {ChildData}}</div>
  4. <router-view @pushData="getChildData"></router-view>
  5. </template>
  6. <script>
  7. export default {
  8. data:function(){
  9. return{
  10. ChildData:"",//定义获取子组件的数据
  11. }
  12. },
  13. methods:{
  14. getChildData (data) {
  15. this.ChildData=data//想要获取子组件的数据,并赋值给自己的ChildData
  16. }
  17. }
  18. }
  19. </script>

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

  1. <template>
  2. <div @click="sendYourData">点我将数据传给父组件</div>
  3. </template>
  4. <script>
  5. export default {
  6. data:function(){
  7. return{
  8. YourData:"我是来自子组件的数据呢",
  9. }
  10. },
  11. methods:{
  12. sendYourData:function () {
  13. this.$emit('pushData',this.YourData)
  14. }
  15. }
  16. }
  17. </script>

发表评论

表情:
评论列表 (有 0 条评论,292人围观)

还没有评论,来说两句吧...

相关阅读