需求:
获取 select
标签的说明文本
方法一:
给 select
标签绑定 ref
属性,通过下列方法来获取对应的 select
的说明文本。
this.$refs[xxx][0].selectedOptions[0].label
this.$refs[xxx][0].selectedOptions[0].innerHTML
this.$refs[xxx][0].selectedOptions[0].innerText
HTML
<tr v-for="v in list" :key="v.id">
<td>
<select :ref="'school-' + v.id" @change="onChange(v.id)">
<option v-for="item in schollList" :key="item.id" :value="item.id">
{{ item.name }}
</option>
</select>
</td>
</tr>
JS
methods: {
onChange(id) {
const _ref = `school-${id}`
if (this.$refs[_ref][0].selectedOptions[0]) {
const schoolName = this.$refs[_ref][0].selectedOptions[0].label
}
}
}
this.$refs[_ref][0].selectedOptions[0]
的数据结构
方法二:
通过属性 ref
和 自定义属性 data-xxx
的结合来获取 select
的说明文本。
HTML
<tr v-for="v in list" :key="v.id">
<td>
<select :ref="'school-' + v.id" @change="onChange(v.id)">
<option v-for="item in schollList" :key="item.id" :value="item.id" :data-sname="item.name">
{{ item.name }}
</option>
</select>
</td>
</tr>
JS
methods: {
onChange(id) {
const _ref = `school-${id}`
if (this.$refs[_ref][0].selectedOptions[0]) {
const schoolName = this.$refs[_ref][0].selectedOptions[0].dataset.sname
}
}
}
通过
data-xxx
自定义的属性都存放在dataset
对象中。