Vue 之孫組件向爺組件通訊

如何把孫組件內特定的數據傳給爺組件?html

例如
把孫組件的名字傳給爺組件並在爺組件上顯示vue

思路
在孫組件被點擊後 emit 事件 1 和孫組件的名字
在父組件上監聽孫組件 emit 出的事件 1,再次 emit 事件 2
在爺組件上監聽父組件 emit 出的事件 2,並觸發處理函數
這個處理函數將父組件傳出的子組件名字顯示在父組件上npm

<!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>
相關文章
相關標籤/搜索