VueJS component not rendering
My components was also not rendering.
In case it's not that obvious, like it was to me, take a look at how you are importing components.
For example, first I had:
import { CurrencyConverter } from "./CurrencyConverter.vue";
And had to remove the brackets, so it looked like this:
import CurrencyConverter from "./CurrencyConverter.vue";
Ofcourse, this means in your component you use the syntax:
export default {
name: "CurrencyConverter",
}
- 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>
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 bynew 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.