Vue实例使用子组件标签报错HelloWorld未定义,请求代码问题排查
Vue组件报错排查及修复
问题分析
- HTML结构错误:代码里重复书写了
<head>标签且未正确闭合,浏览器DOM解析异常会影响Vue正常挂载。 - 组件注册冲突:通过
Vue.component('HelloWorld', {})已经全局注册了组件,但Vue实例的components选项里又重复注册HelloWorld,此时HelloWorld并非本地变量,直接触发Uncaught ReferenceError: HelloWorld is not defined报错,需删除实例中的components配置。 - 模板语法错误:组件模板内的
{{" click to increase !}}存在多余双引号,导致模板解析失败,页面无内容渲染。 - 语法冗余:
methods中mymeth方法末尾多了一个逗号,虽不触发报错,但属于不规范写法。
修复后的完整代码
<html> <head> </head> <body> <script src="https://cdn.jsdelivr.net/npm/vue@2.7.16/dist/vue.js"></script> <div id="app"> <HelloWorld @updated="fct" :numb="firstNumb"/> </div> <script type="text/javascript"> Vue.component('HelloWorld', { template:'<h1 @click="mymeth">click to increase! {{ numb }}</h1>', props: { numb: Number }, methods:{ mymeth(){ this.$emit('updated', this.numb+1); console.log("value firstNumb in child component ", this.numb) } } }); new Vue({ el:'#app', data:{ firstNumb:5 }, methods:{ fct(e){ this.firstNumb=e; console.log("value firstNumb in parent component ", this.firstNumb) } } }); </script> </body> </html>
内容的提问来源于stack exchange,提问作者ftouh yaham
相关产品推荐
相关产品推荐

