在本教程中,我们将讨论从组件外部调用 Vue.js 组件方法的最简洁方法。
让我们看看是否有一种很好的方法可以从 Vue 实例外部调用属于这些组件之一的方法。
在通过 $refs 调用父组件之后,我们可以为子组件设置 ref。
像这样将 ref 添加到子组件:
<my-component ref="childref"></my-component>
像这样将点击事件添加到父级:
<button id="external-button" @click="$refs.childref.increaseCount()">External Button</button>
这是完整的示例:
<!DOCTYPE html> <html> <head> <title>How to Call a Vue.js Component Method From Outside The</title> </head> <body> <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> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <script> new Vue({ el: '#app', components: { 'my-component': { template: '#my-template', data: function() { return { count: 0, }; }, methods: { increaseCount: function() { this.count++; } } }, } }); </script> </body> </html>
Vue 组件是具有名称的可重用实例,因此它们接受与新 Vue、数据、计算、监视、方法相同的选项。
例外是一些特定于 root 的选项,例如 el。
日期:2020-06-02 22:17:24 来源:oir作者:oir