項目中引用了一個UI組件庫,在表單上添加了`ref`屬性,方便提交時驗證。觸發(fā)提交方法時顯示不存在這個方法或this.$refs為undefined。
<u--form labelPosition="left" :model="userInfo" :rules="rules" ref="loginForm">
<u-form-item label="賬號" prop="name" borderBottom ref="username">
<u--input v-model="userInfo.name" placeholder="請輸入賬號" border="surround"></u--input>
</u-form-item>
<u-form-item label="密碼" prop="password" borderBottom ref="password">
<u--input v-model="userInfo.password" placeholder="請輸入密碼" border="surround" type="password"></u--input>
</u-form-item>
<div class="loginBtn"><u-button type="primary" @click="loginApp">登錄</u-button></div>
</u--form>
解決方法:
引入`getCurrentInstance`,t得到當前組件實例,然后用`ctx.$refs`代替`this.$refs`。這里的`ctx`相當于全局this。
<script setup>
import { getCurrentInstance } from 'vue'
// 獲取當前組件實例
const { ctx } = getCurrentInstance();
function loginApp() {
ctx.$refs.loginForm.validate().then(res => {
uni.$u.toast('校驗通過')
}).catch(err => {
uni.$u.toast('校驗失敗')
})
}
<script>
------------------2023/10/27更新---------------------------------
真機調(diào)試時,遇到一個問題,用上面的方法獲取不到`dom`元素。
解決方法:文章來源:http://www.zghlxwxcb.cn/news/detail-731947.html
定義一個ref對象,要和視圖中的`ref``引用名稱相同。文章來源地址http://www.zghlxwxcb.cn/news/detail-731947.html
// 視圖
<u--form labelPosition="left" :model="userInfo" :rules="rules" ref="loginForm">
</u--form>
// js代碼
const loginForm = ref(null)
loginForm.value.validate().then(res => {})
到了這里,關(guān)于uni-app使用vue3,在元素或組件實例上添加ref,用this.$refs顯示undefined的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!