Getting started with Vue

Getting started with Vue

Vue is an amazing front-end framework that is easy to learn and use. But where do you start? I will get you set up and ready to learn Vue using its CDN as its the quickest way to get started. To get the Vue's CDN, head on over to their get started section on the official website here: https://vuejs.org/guide/quick-start.html. After you grab the CDN add it to your HTML and you are ready to go. Firstly, create a div with the id of your choice however 'app' is the most common. like this-

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

The next step is to create a JS file and link it with your HTML. After that, to start using Vue you have to create an instance of it. To do that you write this line of code:

Vue.createApp({}).mount('#app')

This also mounts The Vue instance onto the div we created earlier. Now we can use Vue's features within our code. Lets create a string and print it onto our website. To do this we have to create a data section within our Vue instance.

data(){
        return{
            message: "Hello World!",
}
},

After we have created our message we can go back to our HTML to display it. For us to be able to display this message we have to use it within the div tag we created at the beginning as Vue is mounted on this tag and will only work within it.

<div id="app"> 
<p>{{message}}</p>
</div>

To display a variable in Vue we surround it with double curly brackets and add the name of the variable. Vue will then insert the string and Hello world will display on the web.

Now lets see how to create methods. For this example I will create a button that if clicked will change the message from Hello world! to Goodbye world!.

Firstly, lets create a button:

<p>{{message}}</p>
<button>change message</button>

Now lets head back to the JS file and create a function to change the message.

methods:{
    changeMessage(){
      this.message = "Goodbye world!"
  },
},

Underneath the data section we add our methods. We have to write this. followed by the variables name to tell Vue that the variable that we want to change is within this data section. Now how do we run this function when the button is clicked? Well it's pretty easy all we have to do is add this to our button tag:

<button @click.prevent="changeMessage()">change message</button>

@click tells Vue if this tag is clicked I want this to happen. .prevent is the same as event.preventDefault() in vanilla JS. This just prevents any default things that might happen when you click the button. After that we just put input our functions name and that's it. Now when you click the button the message should change from Hello world! to Goodbye world!.

This is but a fraction of what amazing things Vue can do. This blog just gets you going with the very basics, hopefully it helped in some way.