Vue插值表达式未渲染数据求助:productName等无法正常显示
Vue插值语法未渲染,显示原始{{ }}语法的问题排查与解决
在学习微软官方Vue在线教程时,编写代码后页面未将data中的productName和productDescription渲染为对应字符串,反而直接显示{{ productName }}、{{ productDescription }}原始语法,实际输出与预期不符。
你的代码
index.js
const app = Vue.createApp({ data() { return { productName: 'Book a Cruise to the Moon', productDescription: 'Cruise to the moon in our luxurious shuttle. Watch the astronauts working outside the International Space Station.', // additional properties later }; }, });
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Relecloud Galaxy Tours</title> <link rel="stylesheet" href="./assets/styles.css" /> <!-- TODO: Import Vue.js core library --> <script src="https://unpkg.com/vue@next"></script> </head> <body> <div class="nav-bar"></div> <h1>Relecloud Galaxy Tours</h1> <!-- TODO: Add information display --> <div id="app"> <h2>{{ productName }}</h2> <div>{{ productDescription }}</div> </div> <!-- TODO: Import Vue app --> <script src="./index.js"></script> <script> app.mount('#app'); </script> </body> </html>
问题原因
- Vue版本类型不匹配:你引入的
vue@next默认是运行时构建版本,该版本不含模板编译器,无法解析HTML中的插值语法{{ }},因此直接输出原始代码。 - Vue库加载失败:网络波动或CDN地址问题导致Vue核心库未加载成功,浏览器无法识别Vue语法,自然不会处理插值内容。
- 挂载逻辑异常:虽然你的代码挂载逻辑看似正确,但如果存在选择器拼写错误(比如大小写不匹配),也会导致挂载失败(你的代码已放在body末尾,DOM加载时机问题概率极低)。
解决办法
1. 切换到带编译器的完整Vue版本
将HTML中引入Vue的CDN地址替换为包含模板编译器的完整构建版本,这是最直接的解决方案:
<script src="https://unpkg.com/vue@next/dist/vue.global.js"></script>
2. 确认Vue库正常加载
打开浏览器开发者工具(F12),切换到「网络」标签页,刷新页面,检查Vue资源的加载状态是否为200。如果加载失败,可更换国内镜像CDN:
<script src="https://cdn.jsdelivr.net/npm/vue@next/dist/vue.global.js"></script>
3. 验证挂载逻辑
在挂载代码后添加调试日志,确认Vue实例是否成功挂载:
const vm = app.mount('#app'); console.log('Vue实例挂载成功:', vm);
如果控制台能输出Vue实例信息,说明挂载逻辑正常;若没有输出,检查选择器与DOM元素id是否完全一致(区分大小写)。
修改后的完整HTML示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Relecloud Galaxy Tours</title> <link rel="stylesheet" href="./assets/styles.css" /> <!-- 使用带编译器的完整Vue版本 --> <script src="https://unpkg.com/vue@next/dist/vue.global.js"></script> </head> <body> <div class="nav-bar"></div> <h1>Relecloud Galaxy Tours</h1> <div id="app"> <h2>{{ productName }}</h2> <div>{{ productDescription }}</div> </div> <script src="./index.js"></script> <script> const vm = app.mount('#app'); console.log('挂载成功:', vm); </script> </body> </html>
内容的提问来源于stack exchange,提问作者Muhammad Shafaat Khan
相关产品推荐
相关产品推荐

