Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS component not rendering

Tags:

I have a very basic vueJS app which I'm following from the website.

Here's the code, why is the component not rendering?

HTML

<script src="https://unpkg.com/vue"></script>  <div id="app">   <p>{{ message }}</p> </div>  <div> <ol>   <todo-item></todo-item> </ol> </div> 

JS

new Vue({   el: '#app',   data: {     message: 'Hello Vue.js!'   } })  Vue.component('todo-item', {     template: '<li>This is a list item</li>' }) 
like image 226
qweqwe Avatar asked Jun 28 '17 14:06

qweqwe


2 Answers

  • Use the component inside of the specified el mount element
  • Define the component before initializing the Vue instance with new Vue

Vue.component('todo-item', {    template: '<li>This is a list item</li>'  })    new Vue({    el: '#app',    data: {      message: 'Hello Vue.js!'    }  })
<script src="https://unpkg.com/vue"></script>    <div id="app">    <ol>      <todo-item></todo-item>    </ol>    <p>{{ message }}</p>  </div>    <div>    </div>
like image 169
yuriy636 Avatar answered Sep 18 '22 00:09

yuriy636


Better, you can use the Single File Components to define the todo-item component inside another file:

app.vue

 import TodoItem from './components/todo-item'   new Vue({   el: '#app',   data: {     message: 'Hello Vue.js!'   },   components: {     TodoItem   } }) 

components/todo-item.vue

<template>   <li>This is a list item</li> </template>  <script>   export default {     name: 'todo-item'   } </script> 

In many Vue projects, global components will be defined using Vue.component, followed by new Vue({ el: '#container' }) to target a container element in the body of every page.

This can work very well for small to medium-sized projects, where JavaScript is only used to enhance certain views. In more complex projects however, or when your frontend is entirely driven by JavaScript, these disadvantages become apparent:

  • Global definitions force unique names for every component
  • String templates lack syntax highlighting and require ugly slashes for multiline HTML
  • No CSS support means that while HTML and JavaScript are modularized into components, CSS is conspicuously left out
  • No build step restricts us to HTML and ES5 JavaScript, rather than preprocessors like Pug (formerly Jade) and Babel

All of these are solved by single-file components with a .vue extension, made possible with build tools such as Webpack or Browserify.

like image 22
Yann Bertrand Avatar answered Sep 21 '22 00:09

Yann Bertrand