简体   繁体   中英

Create a custom component in Vue.js

I'm currently learning JavaScript, HTML, and Vue.Js, and now how to work with components. I'm taking an online course which corrects code using a bot.

The assignment is to create a component, greet that produces <div>hello!</div> when it's called using <greet></greet> . To complete the assignment I need to use Vue.Component and the templete -key. I need to set the el -value at new Vue -caller so it matches <div id="app"></div>

This is in my HTML code so far(with script src included):

<body>
    <div id="app">
      <greet="greet"></greet>
    </div>
  </body>

This is my my Vue code so far

new Vue({ el: '#app' })
Vue.component('greet', {
  data() {
    return {
      greet
    }
  },
  template: '<div>hello!</div>'
})

The output on the HTML page is just blank, so I don't understand what I'm missing here.

The output from the bot is:

file.js
    ✓ exists
    ✓ is valid JavaScript
    1) renders the correct markup

There are couple of mistakes here.

First <greet="greet"></greet> doesn't work. There's something calles props in vue (you'll learn it in future) Change that line to <greet></greet>
Then you don't have to use data() to show hello div. Delete the greet from data.
Above steps might fix your fault

When you use the syntax Vue.component() you are registering a component globally, so it can be used by any new Vue instances created afterward. So:

new Vue({ el: '#app' }) // this Vue instance does not contain the greet component because it does not exists yet. 
Vue.component('greet', {
  data() {
    return {

    }
  },
  template: '<div>hello!</div>'
})

Instead:

Vue.component('greet', {
  data() {
    return {

    }
  },
  template: '<div>hello!</div>'
})

new Vue({ el: '#app' }) // this Vue instance will contain the greet component because it was already created and registered.

Also <greet="greet"></greet> is not valid syntax. It should be <greet></greet> .

You should remove greet from data() function. it has no meaning and use.

The final code should look like:

<body>
    <div id="app">
      <greet></greet>
    </div>
</body>


Vue.component('greet', {
  template: '<div>hello!</div>'
})

new Vue({ el: '#app' })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM