什么是ref属性?
ref
是Vue框架中提供的一个特殊属性,它允许我们在模板或组件中标识某个DOM元素或子组件,并且通过该属性可以在Vue实例中访问和操作这些元素或组件。(id的替代者)
ref属性使用方式
- 打标识:DOM元素上添加
ref
属性,组件上添加ref
属性
<input type="text" ref="txtName" value="0"> 或 <student ref="stu"></student> - 获取:this.$refs.xxx
<div id="app">
<input type="text" ref="txtName" value="0">
<student ref="stu"></student>
<button @click="set">设置</button>
</div>
<script>
const student = {
template: ` <div> 序号:{{noIndex}} </div>`,
data() {
return {
noIndex: 0,
}
},
}
let vm = new Vue({
el: '#app',
methods: {
set() {
let $txtName = this.$refs.txtName;//真实DOM元素
let inputValue = $txtName.value;//获取value 值
$txtName.value++;//设置 value 值
let $vc = this.$refs.stu;//获取组件的实例对象(vc)
$vc.noIndex++;
console.log(this.$refs);
}
},
//注册组件
components: { student }
})
</script>