Vue 之孙组件向爷组件通信的实现

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Vue 之孙组件向爷组件通信的实现

  2021-04-03 我要评论

如何把孙组件内特定的数据传给爷组件?

例如

把孙组件的名字传给爷组件并在爷组件上显示

思路

  • 在孙组件被点击后 emit 事件 1 和孙组件的名字
  • 在父组件上监听孙组件 emit 出的事件 1,再次 emit 事件 2
  • 在爷组件上监听父组件 emit 出的事件 2,并触发处理函数
  • 这个处理函数将父组件传出的子组件名字显示在父组件上
<!DOCTYPE html>
<html lang="en" dir="ltr">
 <head>
  <meta charset="utf-8">
  <title></title>
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.7/dist/vue.js"></script>
 </head>
 <body>
  <div id="app">
   child name: {{child}}
   <parent v-on:say2='greeting("child", $event)'></parent>
  </div>
 </body>
 <script>
  Vue.component('parent', {
   template: `
   <div>
    <child v-on:say1='$emit("say2", $event)'></child>
   </div>   `
  })
  Vue.component('child', {
   template: `
    <div>
     child
     <button v-on:click='$emit("say1", "Jack")'>greeting</button>
    </div>
   `
  })
  new Vue({
   el: '#app',
   data: {
    child: '',
   },
   methods: {
    greeting: function (key, value) {
     this[key] = value
    },
   }
  })
 </script>
</html>
您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们