1.当ref和v-for一起使用时,可以直接通过this.$refs[refName]得到:

<template>
    <editor-bar ref="contentChild" v-for="i in 5"></editor-bar>
</template>

<script>
    export default {
        name: "App",
        components: {},
        data(){
            return {}   
        },
        mounted(){
            console.log(this.$refs['contentChild'])
        },
        methods: {},
    }
</script>

 打印结果

2.未使用v-for循环但仍然有多个ref相同的元素时:

<template>
    <p class="title">第一个</p>
    <Children ref="Children"/>
    <p class="title">第一个</p>
    <Children ref="Children"/>
    <p class="title">第一个</p>
    <Children ref="Children"/>
</template>

<script>
    export default {
        name: "App",
        components: {},
        data(){
            return {}   
        },
        mounted(){
            console.log(this.$refs['Children'])
        },
        methods: {},
    }
</script>

若仍然使用上一种情况的方法获取只能得到最后一个元素

 

 找到项目中用到的vue.js文件,\node_modules\vue\package.json文件中的module属性为默认引入的vue.js文件

 打开改文件,搜索$refs,找到此处代码

 使用下方代码替换掉上方图片框选的else中的代码

if (refs.hasOwnProperty(key)) {
    if (Array.isArray(refs[key])) {
        refs[key].push(ref)
    } 
    else {
        refs[key] = [refs[key], ref]
    }
    
} 
else {
    refs[key] = ref;
}

 然后在组件中仍然使用this.$refs[refName]就可以获取到相同ref的元素数组啦

 

Logo

前往低代码交流专区

更多推荐