Vue.js Intro
Vue.js is an open-source model–view–viewmodel JavaScript framework for building user interfaces and single-page applications. It was created by Evan You, and is maintained by him and the rest of the active core team members coming from various companies.
Specifically, we'll look at these key areas
- Getting started
- Building the UI
- Passing data between components
- Handling forms
- Routing
- Fetching data from an API
- Pros and cons
Vue Overview
Vue is a JavaScript framework.
Vue prides itself on being "incrementally adoptable."
In its simplest mode, you can simply include the core Vue scripts in your application then set about building your components.
Beyond that, and for more complex applications, you can use Vue's own CLI to create (and ultimately publish) a Vue project.
As with most other JavaScript frameworks, Vue apps are built as a series of small components that you can then compose together to make bigger features (and ultimately entire applications).
You'll typically write your Vue applications using HTML, CSS and JavaScript (or TypeScript).
Creating a New Vue App
There are two primary ways to start using Vue.
First, you can simply reference the scripts (via a CDN) and start adding components to any HTML page in an existing app.
<!-- development version, includes helpful console warnings -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
Alternatively, you can install the Vue CLI:
npm install -g @vue/cli
Then create and launch a new project:
vue create hello-world
cd hello-world
npm run serve
When you use vue create you'll be given various presets to choose from or you can pick and choose from options like enabling support for TypeScript, unit tests, etc.
Building Your UI with Vue
Vue is all about templates. Here's an example:
<div id="app">
<label>What's your name?
<input v-model="name" placeholder="Your name..."/>
</label>
<span>Hello {{ name }}</span>
</div>
<script src="https://unpkg.com/vue"></script>
<script>
var app = new Vue({
el: '#app',
data: {
name: ''
}
})
</script>
The template is contained within our #app div.
We then create a new Vue app and tell it to use the #app div as its target element.
v-model sets up a binding between the text input and name data property.
As a result, name will always reflect what the user enters into the text input, and if the value of name is changed programmatically this will be reflected in the text input.
We've used the {{ name }} syntax to render the current value of name so we can see it change instantly as we type new values into the text input.
This will get you up and running, but in practice most applications will be made up of several components, composed together to make bigger features.
To turn this greeting into a reusable component, we need a slightly different syntax.
Vue.component('greeting', {
data: function () {
return {
name: ''
}
},
template: `
<div>
<label>What's your name?
<input v-model="name" placeholder="Your name..."/>
</label>
<span>Hello {{ name }}</span>
</div>
`
})
There are some subtle differences between a Vue component and the app we started with:
- We've moved the markup into a template attribute
- data in a component is expressed as a function which returns an object
With these changes we can now render this component wherever we like in our application.
<div id="app">
<greeting/>
</div>
In summary, a Vue application:
- Can be added to an existing HTML page
- Comprises a Vue app and optionally one or more components
- Is written using JavaScript and HTML
- Runs as JavaScript in the browser
Passing Data Around—Vue
We've already seen one way Vue can handle data, storing name directly in our greeting component.
var app = new Vue({
el: '#app',
data: {
name: ''
}
})
The other common option is to pass data in to a component.
Say we wanted to pass a headline to our greeting component:
<greeting headline="Welcome, thanks for being here!" />
Vue enables this via something called props.
Vue.component('greeting', {
data: function () {
return {
name: ''
}
},
props: ['headline'],
template: `
<div>
<h2>{{ headline }}</h2>
<label>What's your name?
<input v-model="name" placeholder="Your name..."/>
</label>
<span>Hello {{ name }}</span>
</div>
`
})
We've added a props array to the component:
props: ['headline'],
This makes our component accept a headline value which we then render using standard interpolation syntax <h2>{{ headline }}</h2>.
Props are the key to unlocking reusable components, making it possible to use the same component in lots of different scenarios, passing different values in each time.
While using data and props works well for many scenarios, you may run into a need for more centralized state in your applications.
One option is to roll your own data "store," whereby you have a central "store" object which is then shared between multiple components.
Alternatively, once you've set off down that road you can just keep on walking until you get to Vuex!
Vuex offers a Vue implementation of the Flux pattern for state management (you may have heard of this other Flux implementation called Redux).
Crucially, as with everything, it pays to keep to the simplest possible solution that meets the needs of your specific application, but it's good to know more advanced options are out there if you need them.
Handling Forms in Vue
We've already seen the core mechanism Vue employs for handling forms: the v-model directive.
You can use v-model to bind most form inputs to data, including text inputs, selects, checkboxes, etc.
Here's the markup for a simple contact form.
<div id="app">
<form @submit.prevent="submit">
<label>
Name:
<input type="text" v-model="name"/>
</label>
<label>
Thoughts?:
<input type="text" v-model="comments"/>
</label>
<input type="submit" value="Submit"/>
</form>
</div>
v-model does the heavy lifting: keeping your component's data in sync with the values entered by the users.
We direct this form to a submit method in the Vue component using @submit and the optional prevent qualifier to prevent the default browser submit behavior.
Here's the corresponding JavaScript.
<script>
var app = new Vue({
el: '#app',
data: {
name: '',
comments: ''
},
methods: {
submit: function(e){
// submit data to API
console.log(`${this.name}:${this.comments}`);
}
}
})
</script>
The submit method will be invoked when the user submits the form, and there we log out the values for name and comments.
For validation, you'd either need to write your own logic in the submit method, or lean on unofficial Vue libraries such as vuelidate and VeeValidate.
Routing in Vue
Vue offers a separate router you can plug in to your application.
You can include it in your HTML page:
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
You're then able to render a router-view in your markup.
<router-view></router-view>
This is where Vue will render content as you move between routes.
You can configure routes in the JavaScript for your app.
<script>
const Home = { template: '<div>Home</div>' }
const Contact = { template: '<div>Contact Us</div>' }
const routes = [
{ path: '/home', component: Home },
{ path: '/contact', component: Contact }
]
const router = new VueRouter({
routes: routes
})
const app = new Vue({
router
}).$mount('#app');
</script>
Here we have two components (Home and Contact).
Then we've declared two routes pointing to these components.
Next, we declare a router and assign our routes to it.
Finally, we create a new Vue app, using the router.
With all this in place, you can now navigate to these two components using the # symbol.
- <your-site-here>/index.html#/home</your-site-here>
- <your-site-here>/index.html#/contact</your-site-here>
You will often need to pass further data along in the route. For example, if you're routing to a details page for a product, you would expect to provide a product id in the route...
- <your-site-here>/index.html#/product/1</your-site-here>
You can configure your routes to accept a parameter:
routes: [
{ path: '/product/:id', component: User }
]
You can then retrieve this id using $route.params.
<h2>
Displaying product details for {{ $route.params.id }}
</h2>
With a little more plumbing you could also capture these route parameters via your component's props and avoid having to use $route.params everywhere in your components.
Fetching Data from an API Using Vue
Chances are your web application will need to fetch data from an API at some point.
Vue remains agnostic on how you approach this, leaving you free to use the native fetch API or any of the many third-party libraries, such as "Axios."
The key is knowing when to make the call, and for this Vue offers a mount lifecycle hook.
<script>
new Vue({
el: '#app',
data(){
return {
tickets: null;
}
},
mounted(){
axios
.get('api/Tickets')
.then(response => (this.tickets = response));
}
})
</script>
Now when this component is mounted:
- a request will be made to api/Tickets
- the returned data will be assigned to tickets
Once we have the data, we can loop over it using Vue's v-for directive and render markup for each item.
<div id="app">
<div v-for="ticket in tickets">
{{ ticket.title }}
</div>
</div>
Pros and Cons
Pros:
- Well-established framework with a battle-tested component model
- The Vue CLI simplifies the JS build process
- Lighter touch library compared to other frameworks such as Angular (the core Vue library handles the essentials with tangential features like routing available in separate libraries)
- Can be incrementally added to enhance existing applications
- You're free to plug in any other JS libraries you might need for your app
- A large existing JS library ecosystem to lean on
- Extensive documentation available
Cons:
- Vue is largely unopinionated about how your application should be structured (only a con if you prefer a more opinionated, prescriptive approach)
- JavaScript! (if you don't like it)
- Vue does a great job of simplifying the data-binding aspects of building your web app, but in the end you're still writing JavaScript!
- While the Vue CLI abstracts some of the details away, if you do decide to build your entire app around Vue, you'll be rubbing up against the JS ecosystem which brings its own complexity (build tools, package managers, compilation for different browsers)
Above article the code snippets in the blue color. This is just an introduction of Vue js framework.

Comments
Post a Comment