父组件:
<template>
<div>
<!-- 给test1组件实例对象绑定一个自定义事件,事件名为fun1,调用函数为testFun1 -->
<test @fun1="testFun1()"></test>
<!-- 自定义事件的ref书写方式 -->
<test2 ref="test_fun2"></test2>
</div>
</template>
<script>
import { test } from 'node:test';
import test2 from './test2'
export default {
name: 'App',
components: { test, test2 },
methods: {
testFun1 () {
console.log(1);
},
tip () {
alert(1);
}
},
mounted () {
// 自定义事件名为:testRef,调用tip函数
this.$refs.test_fun2.$on('testRef', this.tip);
}
}
</script>
子组件:
// test.vue
<template>
<div>
<el-input type="text" @change="changeVal"></el-input>
</div>
</template>
<script>
export default {
name: test,
methods: {
changeVal () {
this.$emit('fun1');
}
}
}
</script>
// test2.vue
<template>
<div>
<el-input type="text" @change="changeVal"></el-input>
</div>
</template>
<script>
export default {
name: test,
methods: {
changeVal () {
this.$emit('testRef');
}
}
}
</script>
注意:
1、通过:ref = 某变量 来添加ref(即添加了:号),如果想获取该ref时需要添加[0]。如:this. r e f s [ r e f s A r r a y ] [ 0 ] ;如果是 r e f = 某字符串时则不需要添加,如: t h i s . refs[refsArray][0];如果是ref = 某字符串时则不需要添加,如:this. refs[refsArray][0];如果是ref=某字符串时则不需要添加,如:this.refs[refsArray];
2、ref需要在dom渲染完成后才会有,在使用的时候必须确保dom已经渲染好。比如在生命周期mounted(){}中调用,或者在this.$nextTick(() => {})中调用;