[英]Call a Vue.js component method from outside the component
假設我有一個包含子組件的主 Vue 實例。 有沒有辦法完全從 Vue 實例外部調用屬於這些組件之一的方法?
這是一個例子:
var vm = new Vue({ el: '#app', components: { 'my-component': { template: '#my-template', data: function() { return { count: 1, }; }, methods: { increaseCount: function() { this.count++; } } }, } }); $('#external-button').click(function() { vm['my-component'].increaseCount(); // This doesn't work });
<script src="http://vuejs.org/js/vue.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="app"> <my-component></my-component> <br> <button id="external-button">External Button</button> </div> <template id="my-template"> <div style="border: 1px solid; padding: 5px;"> <p>A counter: {{ count }}</p> <button @click="increaseCount">Internal Button</button> </div> </template>
所以當我點擊內部按鈕時, increaseCount()
方法被綁定到它的點擊事件,所以它被調用。 無法將事件綁定到外部按鈕,我正在使用 jQuery 監聽其單擊事件,因此我需要一些其他方法來調用increaseCount
。
編輯
似乎這有效:
vm.$children[0].increaseCount();
但是,這不是一個好的解決方案,因為我通過子數組中的索引引用組件,並且對於許多組件,這不太可能保持不變並且代碼的可讀性較差。
最后我選擇了使用Vue 的ref
指令。 這允許從父級引用組件以進行直接訪問。
例如
在我的父實例上注冊了一個組件:
var vm = new Vue({
el: '#app',
components: { 'my-component': myComponent }
});
使用引用在 template/html 中渲染組件:
<my-component ref="foo"></my-component>
現在,我可以在其他地方從外部訪問組件
<script>
vm.$refs.foo.doSomething(); //assuming my component has a doSomething() method
</script>
看這個小提琴的例子: https ://jsfiddle.net/xmqgnbu3/1/
(使用 Vue 1 的舊示例: https ://jsfiddle.net/6v7y6msr/)
為 Vue3 編輯 - 組合 API
子組件必須在setup
中return
要在父組件中使用的函數,否則該函數對父組件不可用。
注意:
<sript setup>
doc不受影響,因為它默認為模板提供了所有的函數和變量。
您可以為子組件設置 ref,然后在父組件中可以通過 $refs 調用:
將 ref 添加到子組件:
<my-component ref="childref"></my-component>
向父級添加點擊事件:
<button id="external-button" @click="$refs.childref.increaseCount()">External Button</button>
var vm = new Vue({ el: '#app', components: { 'my-component': { template: '#my-template', data: function() { return { count: 1, }; }, methods: { increaseCount: function() { this.count++; } } }, } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <my-component ref="childref"></my-component> <button id="external-button" @click="$refs.childref.increaseCount()">External Button</button> </div> <template id="my-template"> <div style="border: 1px solid; padding: 2px;" ref="childref"> <p>A counter: {{ count }}</p> <button @click="increaseCount">Internal Button</button> </div> </template>
可以使用 Vue 事件系統
vm.$broadcast('event-name', args)
和
vm.$on('event-name', function())
這是小提琴:http: //jsfiddle.net/hfalucas/wc1gg5v4/59/
接受答案的稍微不同(更簡單)的版本:
在父實例上注冊一個組件:
export default {
components: { 'my-component': myComponent }
}
使用引用在 template/html 中渲染組件:
<my-component ref="foo"></my-component>
訪問組件方法:
<script>
this.$refs.foo.doSomething();
</script>
假設您在子組件中有一個child_method()
:
export default {
methods: {
child_method () {
console.log('I got clicked')
}
}
}
現在你想從父組件執行child_method
:
<template>
<div>
<button @click="exec">Execute child component</button>
<child-cmp ref="child"></child_cmp> <!-- note the ref="child" here -->
</div>
</template>
export default {
methods: {
exec () { //accessing the child component instance through $refs
this.$refs.child.child_method() //execute the method belongs to the child component
}
}
}
如果要從子組件執行父組件方法:
this.$parent.name_of_method()
注意:不建議像這樣訪問子組件和父組件。
相反,作為最佳實踐,使用 Props & Events 進行父子通信。
請閱讀這篇非常有用的文章
這是從其他組件訪問組件方法的簡單方法
// This is external shared (reusable) component, so you can call its methods from other components
export default {
name: 'SharedBase',
methods: {
fetchLocalData: function(module, page){
// .....fetches some data
return { jsonData }
}
}
}
// This is your component where you can call SharedBased component's method(s)
import SharedBase from '[your path to component]';
var sections = [];
export default {
name: 'History',
created: function(){
this.sections = SharedBase.methods['fetchLocalData']('intro', 'history');
}
}
這是一個簡單的
this.$children[indexOfComponent].childsMethodName();
使用 Vue 3:
const app = createApp({})
// register an options object
app.component('my-component', {
/* ... */
})
....
// retrieve a registered component
const MyComponent = app.component('my-component')
MyComponent.methods.greet();
我不確定它是否正確,但這個方法對我有用。
首先導入包含您要在組件中調用的方法的組件
import myComponent from './MyComponent'
然后調用 MyCompenent 的任何方法
myComponent.methods.doSomething()
在這樣的組件中聲明您的函數:
export default {
mounted () {
this.$root.$on('component1', () => {
// do your logic here :D
});
}
};
並從這樣的任何頁面調用它:
this.$root.$emit("component1");
有時您希望將這些內容包含在您的組件中。 根據 DOM 狀態(當您的 Vue 組件被實例化時,您正在偵聽的元素必須存在於 DOM 中),您可以在 Vue 組件內偵聽組件外部元素上的事件。 假設您的組件外部有一個元素,當用戶單擊它時,您希望您的組件做出響應。
在 html 中,您有:
<a href="#" id="outsideLink">Launch the component</a>
...
<my-component></my-component>
在您的 Vue 組件中:
methods() {
doSomething() {
// do something
}
},
created() {
document.getElementById('outsideLink').addEventListener('click', evt =>
{
this.doSomething();
});
}
如果您將 Vue 3 與<script setup>
糖一起使用,請注意組件的內部綁定是關閉的(從組件外部不可見),您必須使用defineExpose
(請參閱docs )使它們從外部可見。 像這樣的東西:
<script setup lang="ts">
const method1 = () => { ... };
const method2 = () => { ... };
defineExpose({
method1,
method2,
});
</script>
我使用了一個非常簡單的解決方案。 我使用 Vanilla JS 在我選擇的 Vue 組件中包含了一個調用該方法的 HTML 元素,然后觸發點擊!
在 Vue 組件中,我包含了如下內容:
<span data-id="btnReload" @click="fetchTaskList()"><i class="fa fa-refresh"></i></span>
我使用Vanilla JS:
const btnReload = document.querySelector('[data-id="btnReload"]');
btnReload.click();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.