vue3中使用$refs
vue3比vue2烂
·
在vue2中,如果想直接引用页面中的对象,是这样子的:
<template>
<div><input type="text" ref="txt1" value="hello" /></div>
</template>
<script>
export default {
methods:{
test(){
console.log(this.$refs.txt1.value);
},
}
}
</script>
但在vue3中,没有这种歌仔唱了。这破东西,变来变去,极为无聊,徒增学习成本。
在vue3中,没有$refs
这个对象。原先的$emit
变成了context.emit,但不会有context.refs这种东西。要直接使用页面对象,是这样子的:
<template>
<div><input type="text" ref="txt1" value="hello" /></div>
</template>
<script>
import { defineComponent, ref } from "vue";
export default defineComponent({
setup() {
const txt1 = ref();
const test = () => {
console.log(txt1.value.value);
}
return {
txt1,//一定不要忘记在return中返回给外部
test
}
}
});
</script>
或者
<template>
<div><input type="text" ref="txt1" value="hello" /></div>
</template>
<script setup>
import { defineComponent, ref } from "vue";
const txt1 = ref();
const test = () => {
console.log(txt1.value.value);
}
</script>
看看这种代码,我感觉vue3并不比vue2高明,甚至更烂。估计vue4还会来个大改。
2023.08.09
注意如果该对象放在模式对话框里,如果该模式对话框未显示,则该对象的value为空或undefined。
如:
<div>
<!-- 模式对话框 -->
<el-dialog
v-model="detailState.visible"
>
<detail-window
ref="detail1"
@afterUpdated="afterUpdated"
:rId="detailState.id"
/>
<template #footer>
<el-button @click="closeIt">关闭</el-button>
</template>
</el-dialog>
</div>
<script setup>
const detail1 = ref();
console.log(detail1.value);//undefined
</script>
更多推荐
已为社区贡献4条内容
所有评论(0)