1.基础
this.$refs
在vue中ref可以以属性的形式添加给标签或者组件
ref 写在标签上时:this.$refs.ipt
获取的是添加了ref="ipt"
标签对应的dom
元素
ref 写在组件上时:this.$refs['component']
获取到的是添加了ref="component"
属性的这个组件
<template>
//给标签使用
<input type="text" ref="ipt"/>
//给组件使用
<comp-detail ref="component"></list-detail>
<button @click="confirm">确定</button>
</template>
methods:{
confirm(){
console.log(this.$refs.ipt.value) //打印出输入框中的value值
this.$refs['component'].init() //调用组件comp-detail中的init()方法
}
}
2.进阶
1.单循或双循环标签使用,无论那种都要保证ref唯一
例如:可以在ref值后面附带id或不会重复的索引
2.针对上述唯一的ref进行获取
获取:单循环可以直接用$refs获取非单循环可以通过eval()获取
设置 【ref=“xxx”】【ref=“‘xxx’+index”】
就不多说了 简单
实例:设置【:ref=“‘xxx’+id”】或【:ref=“‘xxx’+index”】
<div v-for="(item,index) in topicList" :key="index">
<el-carousel-item v-for="(son,i) in item.questionList" :key="index+i">
<topic :ref="'topicRef'+son.bId"></topic>
//或也可以用索引. 用一个索引会重复,如下
//<topic :ref="'topicRef'+(i+index)"></topic>
</el-carousel-item>
</div>
获取
eval("that.$refs.tagItem" +(x+index))[0]
或
eval("that.$refs.topicRef" +(ele.bId))[0]