Skip to main content

Vue.js Intro

 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

Popular posts from this blog

Another 10 Free Best WooCommerce Extensions and Add-ons in 2020

Another 10 Free Best WooCommerce Extensions and Add-ons in 2020 I found another 10 Extensions and Add-ons that must be helpful to you people are given below Google Analytics Integration As the name implies, this plugin allows you to connect your site to Google Analytics. It only requires you to authenticate the site with your Google Analytics account and you’ll immediately view full analytics data from Google Analytics right from your WordPress dashboard. Link:  https://wordpress.org/plugins/woocommerce-google-analytics-integration/ Booster for WooCommerce This plugin offers various features Bulk Price Converter, Currency Exchange Rates, Prices and Currencies by Country and a lot more to supercharge your WooCommerce store. Link:  https://wordpress.org/plugins/woocommerce-jetpack/ Discount Rules Here’s a plugin that enables you to set rules where a discount could apply. With Discount Rules, you can set a basic percentage-based discounts, or an advanced rule such as applyin...

Firebase - Basic

Firebase - Basic  Firebase is a mobile- and web application development platform, backed by Google, to help developers deliver richer app experiences. Firebase manages its own infrastructure with a nice set of tools to simplify the workflow of the developer by providing them with development kits and an online dashboard. These toolkits are interconnected, scalable and integrable with third party software to overcome complex challenges with standard building blocks. Firebase Features Real-time Database − Firebase supports JSON data and all users connected to it receive live updates after every change. Hosting − The applications can be deployed over secured connection to Firebase servers. Authentication − We can use anonymous, password or different social authentications. Firebase Advantages It is simple and user friendly. No need for complicated configuration. Firebase offers simple control dashboard. The data is real-time, which means that every change will automatically update ...

Top 10 Programming Languages

Top 10 Programming Languages according to the  TIOBE Index for July 2020 C C is a general-purpose, procedural computer programming language supporting structured programming, lexical variable scope, and recursion, with a static type system. By design, C provides constructs that map efficiently to typical machine instructions. Java Java is many developers’ first exposure to the principles of Object-Oriented design. As one of the easiest coding languages to learn, it’s commonly used to teach college students the basics of design patterns and software engineering. Another general-purpose programming language, Java is one of the most popular for enterprise development, perhaps due to its straightforward nature, stability, and large community of developers. As an example, one important project that makes use of Java is the Android Software Developer Kit (SDK), which allows developers to create applications that function on devices that use the Android Operating System. Additionally, we ...