如何從 VueJS 元件外部呼叫元件方法?
通常情況下,我們無法從元件外部呼叫 Vue 元件方法。但是,我們有一種方法可以從外部呼叫元件。我們可以使用 Vue 的ref 指令。此方法允許從父元件引用元件以進行直接訪問。
要應用ref 指令,我們將首先建立一個 id 為“app”的 div 元素。建立 div 元素後,我們可以透過初始化其資料來將 ref 應用於該元素。
語法
以下是 Vue.js 中從元件外部呼叫元件方法的語法:
<my-component ref="foo"></my-component>
這裡,元件名為“my-component”,並且其“ref”屬性設定為另一個元件“foo”。
示例
在您的 Vue 專案中建立兩個檔案 app.js 和 index.html。下面給出了這兩個檔案的程式碼片段及其檔案和目錄結構。將下面的程式碼片段複製貼上到您的 Vue 專案中並執行 Vue 專案。您將在瀏覽器視窗中看到以下輸出。
檔名 - app.js
目錄結構 -- $project/public -- app.js
// Defining the ref Directive var MyComponent = Vue.extend({ template: '<div><p>Hello User</p><ul><li v-for="thing in things">{{ thing }}</li></ul></div>', data: function() { return { things: ['first thing'] }; }, methods: { addThing: function() { this.things.push('New Thing ' + this.things.length); } } }); var vm = new Vue({ el: '#app', components: { 'my-component': MyComponent } }); document.getElementById("externalButton").onclick = function () { vm.$refs.foo.addThing(); };
檔名 - index.html
目錄結構 -- $project/public -- index.html
<!DOCTYPE html> <html> <head> <title> VueJS | v-else directive </title> <!-- Load Vuejs --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div style="text-align: center;"> <h1 style="color: green;"> Welcome to Tutorials Point </h1> </div> <div id="app"> <h1>Component Test</h1> <my-component ref="foo"></my-component> </div> <button id="externalButton">External Button</button> <script src='app.js'></script> </body> </html>
執行以下命令以獲取以下輸出:
C://my-project/ > npm run serve
完整程式碼
讓我們透過組合以上兩個檔案(app.js 和 index.html)來定義一個完整的可執行程式碼。我們現在可以將此程式碼作為 HTML 程式執行。
<!DOCTYPE html> <html> <head> <title> VueJS | v-else directive </title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <h1>Component Test</h1> <my-component ref="foo"></my-component> </div> <button id="externalButton">External Button</button> <script> // Defining the ref Directive var MyComponent = Vue.extend({ template: '<div><p>Hello User</p><ul><li v-for="thing in things">{{ thing }}</li></ul></div>', data: function() { return { things: ['first thing']}; }, methods: { addThing: function() { this.things.push('New Thing ' + this.things.length); } } }); var vm = new Vue({ el: '#app', components: { 'my-component': MyComponent } }); document.getElementById("externalButton").onclick = function() { vm.$refs.foo.addThing(); }; </script> </body> </html>
單擊“外部”按鈕,它將從元件外部呼叫元件方法。
在本文中,我們演示瞭如何在 Vue JS 中從元件外部呼叫元件方法。為此,我們建立了兩個名為 app.js 和 index.html 的檔案。
廣告