The Vue Instance
A little HTML, CSS, & JavaScript knowledge if recommended for this course.
The starter project
Earlier we covered how Vue.js can control either all, or part of our user interface. To get some experience of Vue.js, we are going to now take a simple HTML site, which is a personal site, and apply some Vue.js to create a blog section.
To continue you will need to have downloaded the project starter.
Inside the index.html page you will notice a script at the bottom of the file:
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
This is a link to the Vue framework to enable us to use it in our project. This CDN link will allow us to explore Vue.js, we will look at other methods of setting up Vue projects later in the course.
Creating a script file
To write our Vue.js code we will need a JavaScript file:
- Create a new file in our project folder:
script.js - Link to this file in the index.html:
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<!-- link to script.js -->
<script src="script.js"></script>
</body>
</html>
The createApp function
To get started with Vue, we need to create a new app instance with the createApp function:
// script.js:
Vue.createApp()
Next, we mount our Vue app to the HTML. We need to tell Vue.js which part of the HTML we want to control. Inside the index page, we have a blog section we will use:
<!-- index.html -->
<!-- BLOG SECTION -->
<section id="blog">
<article>
<h3>Master Vue 3</h3>
<p>
I'm baby chambray street art thundercats occupy four loko
church-key disrupt. Shaman neutra bushwick chicharrones, tousled
air plant lomo williamsburg. Listicle aesthetic whatever prism,
ennui glossier asymmetrical scenester austin intelligentsia
cronut raw denim umami mumblecore. Lo-fi meh austin, selfies
hell of tacos 90's vinyl banh mi tbh bicycle rights mumblecore
tumeric.
</p>
<p class="read_more">Read More</p>
</article>
We will be selecting the <section> to control, but the type of element we mount to does not matter.
Mounting our app
The mount method will then be called, passing in the #blog selector to refer to the section:
Vue.createApp().mount("#blog");
The #blog element selector is just like in CSS, we use the # for an id, the dot for a class. We can also pass in an element name, such as section, but be careful that the name is unique.
We can also create multiple unique Vue instances too. If we wanted to also control our header section we could again use createApp, but mount it to a different element:
Vue.createApp().mount("header");
Vue.createApp().mount("#blog");
These are now independent apps, and can have their own data, as we will see next.