如何从组件外部调用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>
点击External按钮时,它将从组件外部调用组件方法。 在本文中,我们演示了如何在Vue JS中从组件外部调用组件方法。为了做到这一点,我们创建了两个文件,分别命名为app.js和index.html。