elementui ref
ElementUI 中使用 ref 的方法
在 ElementUI 中,ref 主要用于获取组件实例或 DOM 元素的引用,方便直接调用组件方法或操作 DOM。以下是几种常见的使用场景和示例:

获取表单组件引用
通过 ref 可以获取表单组件的实例,调用表单验证等方法:

<template>
<el-form ref="formRef" :model="formData">
<el-form-item label="用户名" prop="username">
<el-input v-model="formData.username"></el-input>
</el-form-item>
</el-form>
<el-button @click="validateForm">提交</el-button>
</template>
<script>
export default {
data() {
return {
formData: { username: '' }
};
},
methods: {
validateForm() {
this.$refs.formRef.validate(valid => {
if (valid) {
console.log('表单验证通过');
}
});
}
}
};
</script>
获取表格组件引用
通过 ref 可以操作表格组件,如清除选中状态:
<template>
<el-table ref="tableRef" :data="tableData">
<el-table-column prop="date" label="日期"></el-table-column>
</el-table>
<el-button @click="clearSelection">清除选中</el-button>
</template>
<script>
export default {
data() {
return {
tableData: [{ date: '2023-01-01' }]
};
},
methods: {
clearSelection() {
this.$refs.tableRef.clearSelection();
}
}
};
</script>
获取 Dialog 组件引用
通过 ref 可以控制 Dialog 的显示与隐藏:
<template>
<el-button @click="openDialog">打开对话框</el-button>
<el-dialog ref="dialogRef" title="提示">
<span>这是一段内容</span>
</el-dialog>
</template>
<script>
export default {
methods: {
openDialog() {
this.$refs.dialogRef.visible = true;
}
}
};
</script>
注意事项
ref需要在组件渲染完成后才能访问,避免在mounted生命周期之前调用。- 动态生成的组件(如
v-for循环中的组件)的ref会是一个数组。 - 避免过度使用
ref,优先考虑通过 props 和 events 进行组件通信。
通过合理使用 ref,可以更灵活地操作 ElementUI 组件,实现复杂的交互逻辑。






