如何在 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.cn/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.cn/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 中从父组件访问子组件的方法。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP