注释很详细,直接上代码
新增内容
- 使用ref标记元素或组件
- 通过$refs获取元素或组件实例
源码
App.vue
<template>
<div id="app">
<h1 ref="h1">ref用法演示h1>
<TestComponent ref="testComponent" />
<button @click="OnTap">点击输出button>
div>
template>
<script>
import TestComponent from "./components/TestComponent.vue";
export default {
name: "App",
components: {
TestComponent
},
data() {
return {
};
},
methods: {
OnTap(){
//此处打印出h1元素信息
console.log(this.$refs.h1);
//此处调用TestComponent组件中的方法
this.$refs.testComponent.test();
}
}
};
script>
<style>style>
TestComponent.vue
<template>
<div>
div>
template>
<script>
export default {
methods: {
test() {
console.log('我是Test组件中的方法!!!');
}
}
}
script>
<style lang="less" scoped>
style>
效果演示
