uniapp 动态绑定获取ref

绑定

<view :ref="`name${index}`"></view>

获取

this.$refs[`name$
UniApp 中使用 ref 获取元素 value 为 undefined,可能由多种原因导致,以下是不同情形下的解决办法: ### 渲染顺序问题 页面元素还未完成渲染就尝试获取 ref,会得到 undefined。因为对话框的显示隐藏类似 v-if,控制着页面元素的显示隐藏,若直接获取 ref,页面未来得及渲染实例,就只能拿到 undefined [^2]。 解决办法是等待元素渲染完成后再获取 ref。可以使用 `nextTick` 来确保在下次 DOM 更新循环结束之后执行延迟回调。示例代码如下: ```vue <template> <view> <input ref="myInput" /> <button @click="getValue">获取值</button> </view> </template> <script setup> import { ref, nextTick } from 'vue'; const myInput = ref(null); const getValue = async () => { await nextTick(); const value = myInput.value?.value; console.log(value); }; </script> ``` ### UniApp 和 Vue3 setup 中使用传统 `this.$refs` 问题 在使用 UniApp 和 Vue3 setup 开发时,若直接用传统的 `this.$refs` 来引用组件,会导致报错 `Cannot read property '$refs' of undefined` [^1]。 在 Vue3 的 `setup` 语法糖中,应使用 `ref` 来创建响应式引用。示例代码如下: ```vue <template> <view> <input ref="myInput" /> <button @click="getValue">获取值</button> </view> </template> <script setup> import { ref } from 'vue'; const myInput = ref(null); const getValue = () => { const value = myInput.value?.value; console.log(value); }; </script> ``` ### v-for 绑定动态 ref 问题 使用 v-for 绑定动态 ref 后无法获取元素,是因为元素渲染需要时间,必须等其渲染完成后才能获取 ref,否则将获取不到 [^3]。 可以在合适的时机(如 `onReady` 生命周期函数)来获取 ref。示例代码如下: ```vue <template> <view> <view v-for="(item, index) in list" :key="index"> <input :ref="el => inputs[index] = el" /> </view> <button @click="getValues">获取所有值</button> </view> </template> <script setup> import { ref, onReady } from 'vue'; const list = ref([1, 2, 3]); const inputs = ref([]); const getValues = () => { const values = inputs.value.map(input => input?.value); console.log(values); }; onReady(() => { // 等待页面渲染完成后获取值 getValues(); }); </script> ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值