Home > Article > Web Front-end > What is the reason why ref binding to dom or component fails in vue3 and how to solve it
It is often used in vue3ref
When binding components or dom elements, many times, ref binding is clearly used to bind related components, but ref binding often fails.
The vast majority of cases where ref binding fails is that when the ref is bound to the component, the component has not yet been rendered, so the binding fails.
Or the component is not rendered at the beginning and the ref is not bound. When the component starts to render, the ref also starts to be bound, but the binding of ref and the component is not completed. At this time, problems will occur when using component-related methods. .
The component bound to ref uses v-if
, or its parent component uses v-if
, causing the page to start rendering. At this time, these components are not rendered, so the binding fails.
There are many dialog
pop-up windows and other components in element-plus
. These components are hidden at first and only appear when the user clicks the button. display, so many times the ref starts to be bound to the component when the user clicks the button. At this time, the binding is not completed. If we use the component method through the ref variable, Uncaught TypeError: Cannot read properties of null will appear. (reading 'setCheckedNodes') error
Use the nextTick
method of vue3, let The logic of calling the ref component method can be executed in the next time slice. (Recommended)
function addFilterPropertyRule(row) { let ruleParamObj = JSON.parse(row.hardwareParam) if (ruleParamObj) { makePropertityTree(ruleParamObj, treeData) } addOrEditRuleVisible.value = true currentRuleItem = row if (row.ruleJson) { nextTick(() => { treeRef.value.setCheckedNodes(JSON.parse(row.ruleJson), false) }) } }
Use a delay timer to let the logic of calling the ref component method wait for a while before executing. (Not recommended)
Combined API template references are not specially treated when used internally in v-for. Custom processing of binding functions is required.
<template> <div v-for="(item, i) in list" :ref="el => { if (el) divs[i] = el }"> {{ item }} </div> </template> <script> import { ref, reactive, onBeforeUpdate } from 'vue' export default { setup() { const list = reactive([1, 2, 3]) const divs = ref([]) // 确保在每次更新之前重置ref onBeforeUpdate(() => { divs.value = [] }) return { list, divs } } } </script>
Ref
<template> <div ref="root">This is a root element</div> </template> <script> import { ref, onMounted } from 'vue' export default { setup() { const root = ref(null) onMounted(() => { // DOM 元素将在初始渲染后分配给 ref console.log(root.value) // <div>This is a root element</div> }) return { root } } } </script>
The above is the detailed content of What is the reason why ref binding to dom or component fails in vue3 and how to solve it. For more information, please follow other related articles on the PHP Chinese website!