如何在 Vue.js 中從父元件訪問子元件的方法?


假設您有兩個巢狀元件,即一個元件位於另一個元件內。您將如何從父元件訪問子元件的方法?要從父元件方法訪問子元件方法,您可以使用 ref。或者,您也可以透過方法 this.$root(父元件)訪問父元件的後代,該方法可以使用 this.$children 陣列訪問子元件。同樣,子元件可以透過 this.$parent 訪問其父元件。

Vue.js 主要出於以下兩個原因告誡不要這樣做:

  • 它將父元件和子元件緊密耦合。

  • 子元件可以修改父元件的狀態,因此不可靠。

因此,我們還可以使用 Vue.js 實現的事件介面,該介面允許在元件樹中向上和向下通訊。

  • $on() - 這允許您在要偵聽事件的 Vue 例項上宣告偵聽器。

  • $emit() - 這允許您在同一例項上觸發事件。

示例

複製並貼上以下程式碼片段到您的 Vue 專案中,然後執行 Vue 專案。您將在瀏覽器視窗中看到以下輸出。

  • 檔名 - app.js

  • 目錄結構 -- $project/public -- app.js

// Defining the parent and child events
const events = new Vue({}),
parentComponent = new Vue({
   el: '#parent',
   ready() {
      events.$on('eventGreet', () => {
         this.parentMsg = `Heard the greeting event from Child component ${++this.counter} times..`;
      });
   },
   data: {
      parentMsg: 'Listening for an event..',
      counter: 0
   }
}),
childComponent = new Vue({
   el: '#child',
   methods: {
      greet: function () {
         events.$emit('eventGreet');
         this.childMsg = `Firing the greeting event ${++this.counter} times..`;
      }
   },
   data: {
      childMsg: 'Ready to fire an event.',
      counter: 0
   }
});
  • 檔名 - index.html

  • 目錄結構 -- $project/public -- index.html

<!DOCTYPE javascript>
<javascript>
<head>
   <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
   <body>
      <div id="parent">
         <h2>Parent Component</h2>
         <p>{{parentMsg}}</p>
      </div>
      <div id="child">
         <h2>Child Component</h2>
         <p>{{childMsg}}</p>
         <button v-on:click="greet">Greet</button>
      </div>
      <script src='app.js'></script>
   </body>
</javascript>

執行以下命令以獲取以下輸出:

C://my-project/ > npm run serve	

包含 JavaScript 的完整示例

現在,讓我們組合這兩個檔案 - app.js 和 index.js 以建立一個新的 JavaScript 檔案

<!DOCTYPE javascript>
<javascript>
<head>
   <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
   <body>
      <div id="parent">
         <h2>Parent Component</h2>
         <p>{{parentMsg}}</p>
      </div>
      <div id="child">
         <h2>Child Component</h2>
         <p>{{childMsg}}</p>
         <button v-on:click="greet">Greet</button>
      </div>
      <script>
         
         // Defining the parent and child events
         const events = new Vue({}),
         parentComponent = new Vue({
            el: '#parent',
            ready() {
               events.$on('eventGreet', () => {
                  this.parentMsg = `Heard the greeting event from Child component ${++this.counter} times..`;
               });
            },
            data: {
               parentMsg: 'Listening for an event..',
               counter: 0
            }
         }),
         childComponent = new Vue({
            el: '#child',
            methods: {
               greet: function () {
                  events.$emit('eventGreet');
                  this.childMsg = `Firing the greeting event ${++this.counter} times..`;
               }
            },
            data: {
               childMsg: 'Ready to fire an event.',
               counter: 0
            }
         });
      </script>
   </body>
</javascript>

執行上述程式時,將觸發預設的問候事件。單擊子元件中的“問候”按鈕後,它將顯示 - 觸發問候事件 1 次。

在本教程中,我們討論瞭如何在 Vue.js 中從父元件訪問子元件的方法。

更新於:2023年4月12日

5K+ 次瀏覽

啟動您的職業生涯

完成課程後獲得認證

開始
廣告