Vue中设置按钮焦点时出现Cannot read property 'focus' of undefined错误
First, let's break down why this error pops up only for those three failedProcess values:
When you set this.failedProcess to existOrderSearchProdOrders, stockSearchStockLevels, or cartFetchCouriers, Vue needs to re-render the modal footer to display the "Return to homepage" button. However, Bootstrap's shown.bs.modal event fires before Vue finishes updating the DOM. This means the homeButton ref hasn't been registered yet when your focus method runs, leading to the "undefined" error.
Here's how to fix it:
Step 1: Wait for Vue to Update the DOM
Use this.$nextTick() to delay your focus logic until Vue has completed all pending DOM updates. This ensures the correct button is rendered and its ref is available before you try to call focus().
Step 2: Safeguard Against Undefined Refs
Add checks (or optional chaining if your setup supports it) to confirm the ref exists before accessing its properties. This prevents errors even if something unexpected happens.
Corrected focus Method
If your Vue setup supports optional chaining (Vue 3 or Vue 2 with Babel):
methods: { focus() { this.$nextTick(() => { if (this.failedProcess === 'appGetAccount') { this.$refs.logoutButton?.focus(); } else if (this.failedProcess === 'fetchOrderReportDetails') { this.$refs.existOrdersButton?.$el?.focus(); } else if (this.errorCount < 3 && this.failedProcess !== 'productsFetchProducts') { this.$refs.closeButton?.focus(); } else { this.$refs.homeButton?.$el?.focus(); } }); }, }
For Vue 2 without optional chaining support:
methods: { focus() { this.$nextTick(() => { if (this.failedProcess === 'appGetAccount') { if (this.$refs.logoutButton) { this.$refs.logoutButton.focus(); } } else if (this.failedProcess === 'fetchOrderReportDetails') { if (this.$refs.existOrdersButton && this.$refs.existOrdersButton.$el) { this.$refs.existOrdersButton.$el.focus(); } } else if (this.errorCount < 3 && this.failedProcess !== 'productsFetchProducts') { if (this.$refs.closeButton) { this.$refs.closeButton.focus(); } } else { if (this.$refs.homeButton && this.$refs.homeButton.$el) { this.$refs.homeButton.$el.focus(); } } }); }, }
Why This Works
$nextTick()ensures Vue finishes updating the DOM after changingfailedProcess, so the correct button is present and its ref is registered.- The safeguards prevent the error if the ref is ever undefined for any reason.
This should resolve the error for those three failedProcess values while keeping the focus functionality working for all other cases.
内容的提问来源于stack exchange,提问作者murday1983

