共计 1498 个字符,预计需要花费 4 分钟才能阅读完成。
在 vue2.x 中,能够通过给元素增加 ref=’xxx’ 属性,而后在代码中通过 this.$refs.xxx 获取到对应的元素
然而在 vue3 中时没有 $refs 这个货色的,因而 vue3 中通过 ref 属性获取元素就不能依照 vue2 的形式来获取
vue3 须要借助生命周期办法,起因很简略,在 setup 执行时,template 中的元素还没挂载到页面上,所以必须在 mounted 之后能力获取到元素。
<template> | |
<div ref='box'>I am DIV</div> | |
</template> | |
<script> | |
import {ref,onMounted} | |
export default{setup(){let box = ref(null); | |
onMounted(()=>{console.log(box.value) | |
}); | |
return {box} | |
} | |
} | |
</script> |
如上代码,vue3 中,所有生命周期办法都抽离进来了,须要用时间接 import。这里导入了一个 onMounted
当界面挂载进去的时候,就会主动执行 onMounted 的回调函数,外头就能够获取到 dom 元素
应用过 elementUI <el-form> 的都晓得, 当咱们须要表单校验时,vue2 的写法是在点击事件里传 ref 绑定的名称, 通过 this.$refs[formName]获取 dom 元素, 如下:
<el-button type="primary" @click="submitForm('ruleForm')"> 立刻创立 </el-button>
submitForm(formName) {this.$refs[formName].validate((valid) = >{if (valid) {alert('submit!'); | |
} else {console.log('error submit!!'); | |
return false; | |
} | |
}); | |
}, |
那么 vue3 中没有 this.$refs 又该怎么写呢? 如下:
<el-form :model="addForm" ref="addFormRef" label-width="90px" class="demo-dynamic">
<el-form-item | |
label="标签名称:" | |
prop="newTag" | |
:rules="[{required: true, message: '标签名称不能为空', trigger: 'blur'},{validator: validatePass, trigger: 'blur'}]" | |
> | |
<el-input v-model.trim="addForm.newTag" size="small" placeholder="标签名称(仅反对汉字、英文字母、数字、下划线, 组成 1 - 5 位)"></el-input> | |
</el-form-item> | |
</el-form> | |
<el-button type="primary" @click="submitForm" size="small"> 保 存 </el-button> | |
const {proxy} = getCurrentInstance(); | |
const state = reactive({ | |
addForm: {newTag: '',}, | |
}); |
// 在 setup 函数中,能够应用 ref 函数,用于创立一个响应式数据,当数据产生扭转时,Vue 会自动更新 UI
const addFormRef = ref(null); | |
const submitForm = () = >{addFormRef.value.validate().then(() = >{console.log('校验胜利'); | |
}). | |
catch(() = >{console.log('校验失败'); | |
}); | |
}; |
正文完