You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过$refs修改Vue.js标题后,更新data值页面未同步问题排查

Why isn't my Vue.js heading updating after modifying it via $refs?

Let's break down what's happening here and fix the issue.

The Root Cause

When you run v1.$refs.heading.innerText="BEFORE Change", you're bypassing Vue's data-driven reactivity system and directly manipulating the real DOM element.

Vue manages view updates using its virtual DOM: for your <h1 ref="heading">{{ title }}</h1> element, Vue creates a text node inside the <h1> that's dynamically bound to the title data property. When you overwrite innerText, you replace that bound text node with a new, unbound piece of text.

Later, when you click the button to update this.title, Vue's watcher triggers (which is why you see the alert), but it tries to update the original text node that you've already removed from the DOM. That's why the heading stays stuck on "BEFORE Change" instead of updating to the new title.

The Fix

Instead of directly modifying the DOM, always update your Vue data properties—this lets Vue handle the DOM updates automatically and keeps your data and view in sync. Replace your manual DOM manipulation line with:

v1.title = "BEFORE Change";

With this change, the <h1> will correctly display "BEFORE Change" initially, and when you click the button, it will update to "The VueJS Instance (Updated)" as expected.

A Quick Best Practice

As a general rule in Vue development, avoid direct DOM manipulation unless you have no other option. Vue's reactivity system is designed to keep your data and view synchronized—lean into it instead of fighting against it!

内容的提问来源于stack exchange,提问作者Davit Azizyan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 13:57:55