在vue实例中使用子标签时,错误组件未定义

问题描述 投票:0回答:1

我刚刚开始学习 vuejs,我尝试运行一些代码来应用我所学到的知识,使用

Vue.component('nameOfComponent', { });
在 vue 实例中创建一个基本组件,但没有显示任何内容,并且出现了 Uncaught ReferenceError: HelloWorld 未定义

下面的代码有什么问题?

<html>
<head>
<head>
<body>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/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,
},
components: { HelloWorld },

 methods:{
     fct(e){
    this.firstNumb=e;
    console.log("value firstNumb in parent component ", this.firstNumb)
    },
 
 }
 });
 
 </script>
 </body>
 </html>
vue.js vuejs2
1个回答
0
投票

值得注意的是,Vue 2 已达到 EOL(生命周期结束),如果有的话,您应该学习 Vue 3。 无论如何,对于你的问题...

组件需要分配给一个变量才能在

new Vue()

内正确引用
const HelloWorld = Vue.component(...)
new Vue({
  ...
  components: { HelloWorld },
  ...
})

此外,当直接在 DOM 中添加自定义元素时,您必须使用 kebab-case,如 Vue 2 文档中所述:

只有短横线大小写的名称在 DOM 中直接有效

<div id="app">
  <hello-world @updated="fct" :numb="firstNumb"/>
</div>

纠正其他一些小错误/拼写错误,下面提供了工作代码:

<html>
<head>
<head>
<body>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>


<div id="app">
  <hello-world @updated="fct" :numb="firstNumb"/>
</div>
<script>

const HelloWorld = 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() {
    return {
      firstNumb: 5
    }
  },
  components: { HelloWorld },
  methods:{
    fct(e){
      this.firstNumb=e;
      console.log("value firstNumb in parent component ", this.firstNumb)
    },
  }
});
</script>
</body>
</html>

© www.soinside.com 2019 - 2024. All rights reserved.