Search

VueJs's Articles

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 such as Netlify and Netguru.

Google Bar Chart with Example VueJs
Today,I will learn you how to create Google bar Charts in Vue js. we will show example of Vue Js Google bar Charts. I will make vue js google bar charts example.you can easyliy create google bar charts in vue js. Here follow this example of google bar charts example in vue js. here, I this step create new Vue Project.follwing command vue create chart-project Installation Package Now this step,I will install Package vue-google-charts. npm i vue-google-charts App.vue Here this step, Create a new component called ChartApp.vue and paste the following into it: chart-project/src/components/App.vue <template> <div id="app" style="width:70%;"> <h1 style="padding-left:80px;">Vue Js Google bar Charts Example - nicesnippets.com</h1> <GChart type="BarChart" :data="chartData" :options="chartOptions" /> </div> </template> <script> import { GChart } from "vue-google-charts"; export default { name: "App", components: { GChart }, data() { return { // Array will be automatically processed with visualization.arrayToDataTable function chartData: [ ["Language", "Blog"], ["PHP", 180], ["Laravel", 200], ["Html", 100], ["vue.js", 150], ], chartOptions: { chart: { title: "Company Performance", subtitle: "blog in total: languages" } } }; } }; </script> Add main.js In this last, just add your new component in App.vue and everything should look something like this: chart-project/src/components/main.js import Vue from 'vue' import App from './App.vue' Vue.config.productionTip = false new Vue({ render: h => h(App), }).$mount('#app') i hope you like this article.
Google Pie Chart with Example VueJs
Today,I will learn you how to create Google pie Charts in Vue js. we will show example of Vue Js Google pie Charts. I will make vue js google pie charts example.you can easyliy create google pie charts in vue js. Here follow this example of google pie charts example in vue js. Creating a Project here, I this step create new Vue Project.follwing command vue create chart-project Installation Package Now this step,I will install Package vue-google-charts. npm i vue-google-charts App.vue Here this step, Create a new component called ChartApp.vue and paste the following into it: chart-project/src/components/App.vue <template> <div id="app" style="width:70%;"> <h1 style="padding-left:80px;">Vue Js Google pie Charts Example - nicesnippets.com</h1> <GChart type="pieChart" :data="chartData" :options="chartOptions" /> </div> </template> <script> import { GChart } from "vue-google-charts"; export default { name: "App", components: { GChart }, data() { return { // Array will be automatically processed with visualization.arrayToDataTable function chartData: [ ["Language", "Blog"], ["PHP", 180], ["Laravel", 200], ["Html", 100], ["vue.js", 150], ], chartOptions: { chart: { title: "Company Performance", subtitle: "blog in total: languages" } } }; } }; </script> Add main.js In this last, just add your new component in App.vue and everything should look something like this: chart-project/src/components/main.js import Vue from 'vue' import App from './App.vue' Vue.config.productionTip = false new Vue({ render: h => h(App), }).$mount('#app') i hope you like this article.
VueJs Google Column Chart with Example
Today,I will learn you how to create Google Column Charts in Vue js. we will show example of Vue Js Google Column Charts. I will make vue js google column charts example.you can easyliy create google column charts in vue js. Here follow this example of google column charts example in vue js. Creating a Project here, I this step create new Vue Project.follwing command vue create chart-project Installation Package Now this step,I will install Package vue-google-charts. npm i vue-google-charts App.vue Here this step, Create a new component called ChartApp.vue and paste the following into it: chart-project/src/components/App.vue <template> <div id="app" style="width:70%;"> <h1 style="padding-left:80px;">Vue Js Google Column Charts Example - nicesnippets.com</h1> <GChart type="ColumnChart" :data="chartData" :options="chartOptions" /> </div> </template> <script> import { GChart } from "vue-google-charts"; export default { name: "App", components: { GChart }, data() { return { // Array will be automatically processed with visualization.arrayToDataTable function chartData: [ ["Year", "Sales", "Expenses", "Profit"], ["2017", 1030, 540, 350], ["2018", 1000, 400, 200], ["2019", 1170, 460, 250], ["2020", 660, 1120, 300], ], chartOptions: { chart: { title: "Company Performance", subtitle: "Sales, Expenses, and Profit: 2017-2020" } } }; } }; </script> Add main.js In this last, just add your new component in App.vue and everything should look something like this: chart-project/src/components/main.js import Vue from 'vue' import App from './App.vue' Vue.config.productionTip = false new Vue({ render: h => h(App), }).$mount('#app') It will help you.
Google Line Chart with Example in VueJs
Today,I will learn you how to create Google line Charts in Vue js. we will show example of Vue Js Google line Charts. I will make vue js google line charts example.you can easyliy create google line charts in vue js. Here follow this example of google line charts example in vue js. Creating a Project here, I this step create new Vue Project.follwing command vue create chart-project Installation Package Now this step,I will install Package vue-google-charts. npm i vue-google-charts App.vue Here this step, Create a new component called ChartApp.vue and paste the following into it: chart-project/src/components/App.vue <template> <div id="app" style="width:70%;"> <h1 style="padding-left:80px;">Vue Js Google line Charts Example - nicesnippets.com</h1> <GChart type="LineChart" :data="chartData" :options="chartOptions" /> </div> </template> <script> import { GChart } from "vue-google-charts"; export default { name: "App", components: { GChart }, data() { return { // Array will be automatically processed with visualization.arrayToDataTable function chartData: [ ["Year", "Sales", "Expenses", "Profit"], ["2017", 1030, 540, 350], ["2018", 1000, 400, 200], ["2019", 1170, 460, 250], ["2020", 660, 1120, 300], ], chartOptions: { chart: { title: "Company Performance", subtitle: "Sales, Expenses, and Profit: 2017-2020" } } }; } }; </script> Add main.js In this last, just add your new component in App.vue and everything should look something like this: chart-project/src/components/main.js import Vue from 'vue' import App from './App.vue' Vue.config.productionTip = false new Vue({ render: h => h(App), }).$mount('#app') It will help you.
Vue Js File Download Example with Axios
In this article, I will share with you how to download files in VueJs using Axios with a simple example. as you know files uploading and downloading this a common feature in any web application. so, here i will share file downloading in vuejs with a simple example. just follow the steps.  As we know Axios js is very popular for HTTP requests. you can fire get, post, put, etc request using Axios js in Vue js, node js, react js, etc. but if you need the same requirement to download file response from API and used to give download using Axios js then how you can do that? i will help you to do file downloading using Axios. Axios HTTP code : axios({ url: 'http://localhost:8000/api/get-file', method: 'GET', responseType: 'blob', }).then((response) => { var fileURL = window.URL.createObjectURL(new Blob([response.data])); var fileLink = document.createElement('a'); fileLink.href = fileURL; fileLink.setAttribute('download', 'file.pdf'); document.body.appendChild(fileLink); fileLink.click(); }); HTML Code : <!DOCTYPE html> <html> <head> <title>Download File using Axios Vue JS? - HackTheStuff</title> <script src="https://cdn.jsdelivr.net/npm/vue"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js" integrity="sha256-S1J4GVHHDMiirir9qsXWc8ZWw74PHHafpsHp5PXtjTs=" crossorigin="anonymous"></script> </head> <body> <div id="app"> <button @click="onClick()">DownLoad</button> </div> <script type="text/javascript"> var app = new Vue({ el: '#app', methods: { onClick() { axios({ url: 'http://localhost:8000/my.pdf', method: 'GET', responseType: 'blob', }).then((response) => { var fileURL = window.URL.createObjectURL(new Blob([response.data])); var fileLink = document.createElement('a'); fileLink.href = fileURL; fileLink.setAttribute('download', 'file.pdf'); document.body.appendChild(fileLink); fileLink.click(); }); } } }) </script> </body> </html> i hope you like this article.
VueJs CRUD Example using MongoDB | Express.js | Vue.js | Node.js
This is a step by step MEVN stack tutorial, in this tutorial, we are going to learn how to engender MEVN stack app. (MongoDB, Express.js, Vue.js, Node.js). I will show you how to engender a Full-stack single page application with Vue from scratch. We will engender a simple yet best Student Record Management system. This system efficiently sanctions users to perform CRUD (ENGENDER, READ, UPDATE & EFFACE) operations. We will create our server using Node and Express.js and store student records. We will use MongoDB. We will manage the front-end of the application with Vue.js. So, let us start coding the MEVN Stack app with a practical example. Create a New Vue Project To install Vue project, we must have Vue CLI installed on our development system. Run the following command to install Vue CLI: # npm npm install -g @vue/cli # yarn yarn global add @vue/cli Use the following command to install the vue project. vue create vue-mevn-stack-app Head over to vue project: cd vue-mevn-stack-app Run command to start the app on the browser: npm run serve Adding Bootstrap in Vue 2 Let us run the below command to install the Bootstrap 4 UI Framework. npm install bootstrap # or yarn add bootstrap Import the Bootstrap framework path inside the main.js file. Now, you can use Bootstrap UI components in your vue app. import Vue from 'vue' import App from './App.vue' import router from './router' import 'bootstrap/dist/css/bootstrap.min.css' Vue.config.productionTip = false new Vue({ router, render: h => h(App) }).$mount('#app') Build Vue Components Head over to src/components directory, here we have to create the following components. These components will handle the data in our full-stack Vue.Js application. CreateComponent.vue EditComponent.vue ListComponent.vue Open src/CreateComponent.vue file and add the following code inside of it. <template> <div class="row justify-content-center"> <div class="col-md-6"> <!-- Content goes here --> </div> </div> </template> <script> export default { data() { return { } } } </script> </div> Open src/EditComponent.vue file and place code inside of it. <template> <div class="row justify-content-center"> <div class="col-md-6"> <!-- Update Student content --> </div> </div> </template> <script> export default { data() { return { } } } </script> Open src/ListComponent.vue file and add the below code in it. <template> <div class="row justify-content-center"> <div class="col-md-6"> <!-- Display Student List --> </div> </div> </template> <script> export default { data() { return { } } } </script> Enable Vue Router Open src/router/index.js and replace the existing code with the following code. import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter) const routes = [ { path: '/', name: 'home', component: () => import('../components/CreateComponent') }, { path: '/view', name: 'view', component: () => import('../components/ListComponent') }, { path: '/edit/:id', name: 'edit', component: () => import('../components/EditComponent') } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router Setting Up Navigation with Bootstrap and Router View in Vue Go to src/App.vue file, here we define the Bootstrap Navigation component, router-view directive and the router-link directive. The <router-link> is the component for facilitating user navigation in a router-enabled vue app. The <router-view> component is the main component that is responsible for rendering the matched component for the provided path. <template> <div> <!-- Nav bar --> <nav class="navbar navbar-dark bg-primary justify-content-between flex-nowrap flex-row"> <div class="container"> <a class="navbar-brand float-left">MEVN Stack Example | LaravelCode</a> <ul class="nav navbar-nav flex-row float-right"> <li class="nav-item"> <router-link class="nav-link pr-3" to="/">Create Student</router-link> </li> <li class="nav-item"> <router-link class="nav-link" to="/view">View Students</router-link> </li> </ul> </div> </nav> <!-- Router view --> <div class="container mt-5"> <router-view></router-view> </div> </div> </template> Add Axios in Vue.js 2 to Handle HTTP Requests Run command to install Axios: npm install axios # or yarn add axios Axios is a promise based HTTP client for the browser and node.js,  Build Form in Vue with Bootstrap 4 We require to store the data in the MEVN stack app, so we need to build a vue form using Bootstrap Form component. Check out our previous tutorial detailed tutorial on – Form Validation in Vue with Vuelidate. Open components/CreateComponent.vue file, then place the following code in it. <template> <div class="row justify-content-center"> <div class="col-md-6"> <h3 class="text-center">Create Student</h3> <form @submit.prevent="handleSubmitForm"> <div class="form-group"> <label>Name</label> <input type="text" class="form-control" v-model="student.name" required> </div> <div class="form-group"> <label>Email</label> <input type="email" class="form-control" v-model="student.email" required> </div> <div class="form-group"> <label>Phone</label> <input type="text" class="form-control" v-model="student.phone" required> </div> <div class="form-group"> <button class="btn btn-danger btn-block">Create</button> </div> </form> </div> </div> </template> <script> export default { data() { return { student: { name: '', email: '', phone: '' } } }, methods: { handleSubmitForm() { } } } </script> We created a basic form with name, email and phone number field. We created a beautiful form using Bootstrap form component. The student object works with two-way data binding approach; it merely means that any data-related changes affecting the model are immediately propagated to the matching view. Here is the form which you can check in the browser. Setting up Node Server Environment Now, we need to create REST APIs using Node + Express & MongoDB in Vue application. Create backend folder at the root of Vue project. mkdir backend && cd backend Generate separate package.json for node server. npm init Run command to install the following dependencies for Node/Express js. npm i body-parser cors express mongoose Also, install a nodemon server as a development dependency. So that we do not need to restart every time, we change our server code. Install nodemon as a development dependency, It automates the server starting process. npm install nodemon # or yarn add nodemon Configure & Start MongoDB Database Create backend/database.js file at the root of your node application. Next, add the given code in it. module.exports = { db: 'mongodb://localhost:27017/vuecrudmevn' } In this tutorial, we are working with MongoDB to store students data, so you must set up MongoDB on your development system. You can follow this tutorial for the installation guidance at Install MongoDB on macOS, Linux and Windows. Open the terminal window and run the following command to start the MongoDB on your local machine. mongod --config /usr/local/etc/mongod.conf brew services start mongodb-community@4.2 mongo Create Mongoose Model Create models/Student.js and paste the below code inside the file. We will define name, email and phone values inside the Student model. const mongoose = require('mongoose'); const Schema = mongoose.Schema; let studentSchema = new Schema({ name: { type: String }, email: { type: String }, phone: { type: Number }, }, { collection: 'students' }) module.exports = mongoose.model('Student', studentSchema) Create Route in Node/Express App Create a backend/routes directory; here, we have to create student.route.js file and place all the given below code inside of it. const express = require('express'); const studentRoute = express.Router(); // Student model let StudentModel = require('../models/Student'); studentRoute.route('/').get((req, res) => { StudentModel.find((error, data) => { if (error) { return next(error) } else { res.json(data) } }) }) studentRoute.route('/create-student').post((req, res, next) => { StudentModel.create(req.body, (error, data) => { if (error) { return next(error) } else { res.json(data) } }) }); studentRoute.route('/edit-student/:id').get((req, res) => { StudentModel.findById(req.params.id, (error, data) => { if (error) { return next(error) } else { res.json(data) } }) }) // Update student studentRoute.route('/update-student/:id').post((req, res, next) => { StudentModel.findByIdAndUpdate(req.params.id, { $set: req.body }, (error, data) => { if (error) { return next(error); } else { res.json(data) console.log('Student successfully updated!') } }) }) // Delete student studentRoute.route('/delete-student/:id').delete((req, res, next) => { StudentModel.findByIdAndRemove(req.params.id, (error, data) => { if (error) { return next(error); } else { res.status(200).json({ msg: data }) } }) }) module.exports = studentRoute; We defined the routes these routes will communicate with the server using the Axios library. We can perform CRUD operation using the GET, POST, UPDATE & DELETE methods. Create the backend/app.js file and place the following code that contains the Node server settings. let express = require('express'), cors = require('cors'), mongoose = require('mongoose'), database = require('./database'), bodyParser = require('body-parser'); // Connect mongoDB mongoose.Promise = global.Promise; mongoose.connect(database.db, { useNewUrlParser: true, useUnifiedTopology: true }).then(() => { console.log("Database connected") }, error => { console.log("Database could't be connected to: " + error) } ) const studentAPI = require('../backend/routes/student.route') const app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cors()); // API app.use('/api', studentAPI) // Create port const port = process.env.PORT || 4000; const server = app.listen(port, () => { console.log('Connected to port ' + port) }) // Find 404 app.use((req, res, next) => { next(createError(404)); }); // error handler app.use(function (err, req, res, next) { console.error(err.message); if (!err.statusCode) err.statusCode = 500; res.status(err.statusCode).send(err.message); }); Also, don’t forget to register the app.js value inside the “main” property in package.json file. { "name": "vue-mevn-stack", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "body-parser": "^1.19.0", "cors": "^2.8.5", "express": "^4.17.1", "mongoose": "^5.9.10" }, "devDependencies": { "nodemon": "^2.0.3" } } Start Node/Express App We have built following API using Node and Express in Vue.js. Method API GET http://localhost:4000/api POST /api/create-student GET /api/edit-student/:id POST /api/update-student/:id DELETE /api/delete-student/:id Open a new terminal window and start the MongoDB: mongo Open a new terminal window and start the nodemon server: nodemon You can view server running on http://localhost:4000/api Open another terminal window and start the vue app: npm run serve You can view vue app running on http://localhost:8080 Create Student Data with Axios POST The Axios post method takes the REST API and makes the POST request to the server. It creates the student data that we are adding in the mongoDB database. Once the data is sent to the server, you can then check the stored data on http://localhost:4000/api Add the given below code inside the components/CreateComponent.vue file. <template> <div class="row justify-content-center"> <div class="col-md-6"> <h3 class="text-center">Create Student</h3> <form @submit.prevent="handleSubmitForm"> <div class="form-group"> <label>Name</label> <input type="text" class="form-control" v-model="student.name" required> </div> <div class="form-group"> <label>Email</label> <input type="email" class="form-control" v-model="student.email" required> </div> <div class="form-group"> <label>Phone</label> <input type="text" class="form-control" v-model="student.phone" required> </div> <div class="form-group"> <button class="btn btn-danger btn-block">Create</button> </div> </form> </div> </div> </template> <script> import axios from "axios"; export default { data() { return { student: { name: '', email: '', phone: '' } } }, methods: { handleSubmitForm() { let apiURL = 'http://localhost:4000/api/create-student'; axios.post(apiURL, this.student).then(() => { this.$router.push('/view') this.student = { name: '', email: '', phone: '' } }).catch(error => { console.log(error) }); } } } </script> Show Data List & Delete Data in Vue Now, we will show the data in the tabular form using Bootstrap Table components, and we will make the axios.get() request to render the data from the server. Add the given below code inside the components/ListComponent.vue file. <template> <div class="row"> <div class="col-md-12"> <table class="table table-striped"> <thead class="thead-dark"> <tr> <th>Name</th> <th>Email</th> <th>Phone</th> <th>Actions</th> </tr> </thead> <tbody> <tr v-for="student in Students" :key="student._id"> <td>{{ student.name }}</td> <td>{{ student.email }}</td> <td>{{ student.phone }}</td> <td> <router-link :to="{name: 'edit', params: { id: student._id }}" class="btn btn-success">Edit </router-link> <button @click.prevent="deleteStudent(student._id)" class="btn btn-danger">Delete</button> </td> </tr> </tbody> </table> </div> </div> </template> <script> import axios from "axios"; export default { data() { return { Students: [] } }, created() { let apiURL = 'http://localhost:4000/api'; axios.get(apiURL).then(res => { this.Students = res.data; }).catch(error => { console.log(error) }); }, methods: { deleteStudent(id){ let apiURL = `http://localhost:4000/api/delete-student/${id}`; let indexOfArrayItem = this.Students.findIndex(i => i._id === id); if (window.confirm("Do you really want to delete?")) { axios.delete(apiURL).then(() => { this.Students.splice(indexOfArrayItem, 1); }).catch(error => { console.log(error) }); } } } } </script> <style> .btn-success { margin-right: 10px; } </style> To delete the student object from the database, we defined the deleteStudent() function and bound it to click event with an id parameter. The apiURL contains the api/delete-student/:id API, to find out the index of the clicked student data index from the Students array, we took the help of findIndex() method. Update Data with POST Request Add the following code inside the components/EditComponent.vue file. <template> <div class="row justify-content-center"> <div class="col-md-6"> <h3 class="text-center">Update Student</h3> <form @submit.prevent="handleUpdateForm"> <div class="form-group"> <label>Name</label> <input type="text" class="form-control" v-model="student.name" required> </div> <div class="form-group"> <label>Email</label> <input type="email" class="form-control" v-model="student.email" required> </div> <div class="form-group"> <label>Phone</label> <input type="text" class="form-control" v-model="student.phone" required> </div> <div class="form-group"> <button class="btn btn-danger btn-block">Update</button> </div> </form> </div> </div> </template> <script> import axios from "axios"; export default { data() { return { student: { } } }, created() { let apiURL = `http://localhost:4000/api/edit-student/${this.$route.params.id}`; axios.get(apiURL).then((res) => { this.student = res.data; }) }, methods: { handleUpdateForm() { let apiURL = `http://localhost:4000/api/update-student/${this.$route.params.id}`; axios.post(apiURL, this.student).then((res) => { console.log(res) this.$router.push('/view') }).catch(error => { console.log(error) }); } } } </script> i hope you like this article.
Form Validation in VueJs using Vuelidate
This is a comprehensive Vue.js 2+ Form tutorial. In this tutorial, we are going to learn how to engender Forms in Vue.js from scratch and additionally going to cover how to do client-side Form validation in Vue application utilizing the Vuelidate package. We all ken there are two types of Form validation. Server-side form validation: It is an another way to validate HTML form data. It includes sundry input fields, text-area, numerical, string values, input length, numeric value, valid email, etc. Client-side form validation: We validate form data before sending it to the server. In this process, we make sure that all the required form values are correctly filled. Let’s understand what form validation is? We often see various types of forms on almost every site we visit, and we see different kinds of messages such as: This is a required field. Please provide a valid email. Please enter your phone number in particular format xxx-xxx-xxxx. Your password should be or between 6 and 15 characters long and contain a unique set of characters. Form validation is a simple process in which you enter data in the form and browsers makes sure whether your entered data is in the proper format or not and display either of the given above message. This entire process is known as form validation. Getting Started with Vue.js This tutorial guides on creating and validating a basic user form. First, install the latest Vue CLI 4 on your local development system for working with Vue. npm install -g @vue/cli Download Vue project by following the below command. vue create vue-form-validation Get inside the project folder. cd vue-form-validation Use the following command to start the Vue app in the browser. npm run serve Create & Configure Form Component in Vue Go to components folder and create FormValidation.vue file in it, however, you can name it anything you want and be consistent with the same file name throughout the app. In this file we will write all the code that requires for building and validating the form. <template> <div class="container" style="max-width: 500px; text-align: left"> <div class="row"> <div class="alert alert-success" role="alert"> <h2 class="alert-heading">Vue Form Validation Example</h2> </div> </div> </div> </template> Next, register the file in the views template, so go to views > Home.vue and import and register the FormValidation.vue component as given below. <template> <div class="home"> <FormValidation></FormValidation> </div> </template> <script> // @ is an alias to /src import FormValidation from '@/components/FormValidation.vue' export default { name: 'Home', components: { FormValidation } } </script> Adding Bootstrap 4 in Vue To create a Form, we are going to use the Bootstrap 4 UI framework. Though, there are various plugins available to integrate Bootstrap in Vue. However, we are going to add the Bootstrap via CDN in Vue. Go to public > index.html file and add the Bootstrap CDN path in the header section. <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" /> Install and Configure Vuelidate in Vue App To cover the client-side form validation, we are going to rely on Vuelidate module. The Vuelidate is a powerful, simple and lightweight model-based library which offers easy form validation for Vue.js Here are some of the powerful features we get with Vuelidate: Model-based Contextified validators Decoupled from templates Support for nested models Support for function composition Support for collection validations Dependency free, minimalistic library Easy to use with custom validators (e.g., Moment.js) Validates different data sources: Vuex getters, computed values, etc. Run command to install Vuelidate package. # NPM npm install vuelidate --save # Yarn yarn add vuelidate We have to import the Vuelidate library in the src/main.js file and define in the Vue.use(Vuelidate) method. This way, we can take advantage of this plugin and use it globally for all the components that require to be validated. import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' import Vuelidate from 'vuelidate' Vue.use(Vuelidate) Vue.config.productionTip = false new Vue({ router, store, render: h => h(App) }).$mount('#app') Build & Validate User Registration Form in Vue.js 2+ with Vuelidate Let us create a simple form and check out the simple form validation example. We will be validating a user registration form. Go back to the FormValidation.vue file that we created at the starting of this tutorial and add the following code: <template> <div class="container" style="max-width: 500px; text-align: left"> <div class="alert alert-success" role="alert"> <h2 class="alert-heading">Vue Form Validation Example</h2> </div> <form @submit.prevent="handleSubmit"> <div class="form-group"> <label for="name">Name</label> <input type="text" v-model="userForm.name" id="name" name="name" class="form-control" :class="{ 'is-invalid': isSubmitted && $v.userForm.name.$error }" /> <div v-if="isSubmitted && !$v.userForm.name.required" class="invalid-feedback">Name field is required</div> </div> <div class="form-group"> <label for="email">Email</label> <input type="email" v-model="userForm.email" id="email" name="email" class="form-control" :class="{ 'is-invalid': isSubmitted && $v.userForm.email.$error }" /> <div v-if="isSubmitted && $v.userForm.email.$error" class="invalid-feedback"> <span v-if="!$v.userForm.email.required">Email field is required</span> <span v-if="!$v.userForm.email.email">Please provide valid email</span> </div> </div> <div class="form-group"> <label for="mobile">Mobile</label> <input type="text" v-model="userForm.mobile" id="mobile" name="mobile" class="form-control" :class="{ 'is-invalid': isSubmitted && $v.userForm.mobile.$error }" /> <div v-if="isSubmitted && $v.userForm.mobile.$error" class="invalid-feedback"> <span v-if="!$v.userForm.mobile.required">Mobile field is required</span> </div> </div> <div class="form-group"> <label for="gender">Gender</label> <div class="form-group" :class="{ 'is-invalid': isSubmitted && $v.userForm.gender.$error }"> <div class="form-check form-check-inline" :class="{ 'is-invalid': isSubmitted && $v.userForm.gender.$error }"> <input class="form-check-input" type="radio" name="gender" v-model="userForm.gender" id="gender1" value="male"> <label class="form-check-label" for="gender1">Male</label> </div> <div class="form-check form-check-inline" :class="{ 'is-invalid': isSubmitted && $v.userForm.gender.$error }"> <input class="form-check-input" type="radio" name="gender" v-model="userForm.gender" id="gender2" value="female"> <label class="form-check-label" for="gender2">Female</label> </div> <div v-if="isSubmitted && $v.userForm.gender.$error" class="invalid-feedback"> <span v-if="!$v.userForm.gender.required">This field is required</span> </div> </div> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" v-model="userForm.password" id="password" name="password" class="form-control" :class="{ 'is-invalid': isSubmitted && $v.userForm.password.$error }" /> <div v-if="isSubmitted && $v.userForm.password.$error" class="invalid-feedback"> <span v-if="!$v.userForm.password.required">Password field is required</span> <span v-if="!$v.userForm.password.minLength">Password should be at least 5 characters long</span> </div> </div> <div class="form-group"> <label for="confirmPassword">Confirm Password</label> <input type="password" v-model="userForm.confirmPassword" id="confirmPassword" name="confirmPassword" class="form-control" :class="{ 'is-invalid': isSubmitted && $v.userForm.confirmPassword.$error }" /> <div v-if="isSubmitted && $v.userForm.confirmPassword.$error" class="invalid-feedback"> <span v-if="!$v.userForm.confirmPassword.required">Confirm Password field is required</span> <span v-else-if="!$v.userForm.confirmPassword.sameAsPassword">Passwords should be matched</span> </div> </div> <div class="form-group form-check"> <input type="checkbox" v-model="userForm.accept" @change="$v.userForm.accept.$touch()" id="accept" class="form-check-input"> <label class="form-check-label" :class="{ 'is-invalid': isSubmitted && $v.userForm.accept.$error }" for="accept">Accept terms   conditions</label> <div v-if="isSubmitted && $v.userForm.accept.$error" class="invalid-feedback"> <span v-if="!$v.userForm.accept.required">Accept terms and conditions</span> </div> </div> <div class="form-group"> <button class="btn btn-danger btn-block">Register</button> </div> </form> </div> </template> <script> import { required, email, minLength, sameAs } from "vuelidate/lib/validators"; export default { data() { return { userForm: { name: "", email: "", mobile: "", gender: "", password: "", confirmPassword: "", accept: "" }, isSubmitted: false }; }, validations: { userForm: { name: { required }, email: { required, email }, mobile: { required }, gender: { required }, password: { required, minLength: minLength(5) }, confirmPassword: { required, sameAsPassword: sameAs('password') }, accept: { required (val) { return val } } } }, methods: { handleSubmit() { this.isSubmitted = true; this.$v.$touch(); if (this.$v.$invalid) { return; } alert("SUCCESS!" + JSON.stringify(this.userForm)); } } }; </script> <style lang="scss"> .form-group > label { font-weight: 600; } </style> Let us break it down everything we did in the above Form template, and we tried to cover the validation for the name, email, mobile number, gender, password, and password match form fields in the Vue validation example. We imported teh Vuelidate’s validators inside the script tag like required, email, minLength, and sameAs. We used the v-model with HTML input fields; this model bind user object properties with the app component data. Validation properties are set inside the validations: { } object inside the Vue component. The validations property creates an object inside the $v: Object. It can be accessed using the Vue DevTools:
Build Dynamic Data Table in Vue.js 2+ with Vuetify
In this tutorial, we are going to learn how to build a customizable and pageable data table in Vue application utilizing the Vuetify plugin. We will withal optically canvass how to integrate data sorting and filtering feature very facilely in Vue.js 2+. What is Data Table? A table is a relegation of data in rows and columns, or probably in a more perplexed structure. Tables are extensively utilized for data analysis, communication, and research and can be utilized in sundry domains such as print media, computer software, architectural elaboration, traffic signs, and many other places. Data tables illustrate information in a more organizable manner in a grid-like composition that contains rows and columns. The architecture of a table is such that a utilizer can expeditiously scan the exhibited information. A data table organizes information using column and rows, and a general DataTable has the following components: Columns Column header names Rows Footers Pagination Getting Started Create Vue project by using the following command. vue create vue-data-table Get inside the project directory. cd vue-data-table Start the app in the browser. npm run serve Install & Configure Vuetify Plugin Creating a user-friendly application is a challenge in real-world. Vuetify is a powerful Vue UI Library with beautifully handcrafted Material Design UI Components. Vuetify offers 100% support for Vue, and comes with cleaner, semantic, and reusable UI components that lets you create a beautiful user interface in very less time.. You can use the following command to install Vuetify plugin in Vue. npm install vuetify Enable the Vuetify package globally in Vue by adding the following code in the main.js. // main.js import Vue from 'vue' import App from './App.vue' import Vuetify from "vuetify"; import "vuetify/dist/vuetify.min.css"; Vue.use(Vuetify); new Vue({ render: h => h(App) }).$mount('#app') Open public/index.html file and add the Google fonts and Material Design Icons CSS in Vue app. <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/@mdi/font@4.x/css/materialdesignicons.min.css" rel="stylesheet"> Vuetify Simple Table Example in Vue The v-simple-table directive creates the table component in Vue; it needs to be placed inside your Vue component and should wrap the table tag. <template> <v-simple-table> <template v-slot:default> <thead> <tr> <th class="text-left">Name</th> <th class="text-left">Calories</th> </tr> </thead> <tbody> <tr v-for="food in FOOD" :key="food.name"> <td>{{ food.name }}</td> <td>{{ food.calories }}</td> </tr> </tbody> </template> </v-simple-table> </template> <script> export default { data () { return { FOOD: [ { name: 'Burger', calories: 660, }, { name: 'Sandwich', calories: 660, }, { name: 'Cheese Whopper', calories: 790, }, { name: 'Bacon King', calories: 1150, }, { name: 'Farmhouse', calories: 1220, }, { name: 'Grilled Chicken', calories: 470, }, { name: 'Snickers Pie', calories: 300, }, { name: 'Veggie Burger', calories: 390, }, { name: 'Donut', calories: 500, }, { name: 'Grilled Hot Dog', calories: 310, }, { name: 'French Fry', calories: 380, }, ], } }, } </script> FOOD is an array that contains some dummy food data in JSON format. The v-for directive is iterating FOOD array and displaying the data with the table component. Fixed Header Table Example We should add the fixed-header property along with height property in v-simple-table directive to make the table header fixed. <template> <v-simple-table fixed-header height="400px"> <template v-slot:default> <thead> <tr> <th class="text-left">Name</th> <th class="text-left">Calories</th> </tr> </thead> <tbody> <tr v-for="food in FOOD" :key="food.name"> <td>{{ food.name }}</td> <td>{{ food.calories }}</td> </tr> </tbody> </template> </v-simple-table> </template> <script> export default { data () { return { FOOD: [ { name: 'Burger', calories: 660, }, { name: 'Sandwich', calories: 660, }, { name: 'Cheese Whopper', calories: 790, }, { name: 'Bacon King', calories: 1150, }, { name: 'Farmhouse', calories: 1220, }, { name: 'Grilled Chicken', calories: 470, }, { name: 'Snickers Pie', calories: 300, }, { name: 'Veggie Burger', calories: 390, }, { name: 'Donut', calories: 500, }, { name: 'Grilled Hot Dog', calories: 310, }, { name: 'French Fry', calories: 380, }, ], } }, } </script> Table Dark theme To update the table current theme to dark theme can be done by just adding dark tag to v-simple-table component. <template> <v-simple-table dark> <template v-slot:default> <thead> <tr> <th class="text-left">Name</th> <th class="text-left">Calories</th> </tr> </thead> <tbody> <tr v-for="food in FOOD" :key="food.name"> <td>{{ food.name }}</td> <td>{{ food.calories }}</td> </tr> </tbody> </template> </v-simple-table> </template> <script> export default { data () { return { FOOD: [...], } }, } </script> Here is how the table looks in Vue when updated to dark theme. Build Data Table in Vue.js Next, we are going to create Data Table in Vue using Vuetify plugin. The v-data-table component is recommended for showing data in the table form. It comes with some of the core features of DataTable, such as sorting, searching, pagination, inline-editing, and row selection. <template> <v-data-table dark :headers="headers" :items="food" :items-per-page="7" class="elevation-1" ></v-data-table> </template> <script> export default { data () { return { headers: [ { text: 'Food Items (Nutrition 100g)', align: 'start', sortable: false, value: 'name', }, { text: 'Energy', value: 'energy' }, { text: 'Protein', value: 'protein' }, { text: 'Fat', value: 'fat' }, { text: 'Carbohydrate', value: 'carbohydrate' }, { text: 'Sodium', value: 'sodium' }, ], food: [ { name: 'Muesli (Almond)', energy: 201, protein: 5.0, fat: 34, carbohydrate: 5.5, sodium: '1.5%' }, { name: 'Wholegrain Rolled Oats', energy: 301, protein: 3.0, fat: 54, carbohydrate: 3.5, sodium: '2.5%' }, { name: 'Almond Milk', energy: 130, protein: 6.0, fat: 24, carbohydrate: 3.9, sodium: '3.5%' }, { name: 'Firm Tofu', energy: 101, protein: 2.0, fat: 25, carbohydrate: 2.1, sodium: '0.5%' }, { name: 'Hummus', energy: 709, protein: 8.4, fat: 10.8, carbohydrate: 4.6, sodium: '2.5%' }, { name: 'Peanut Butter', energy: 2580, protein: 28, fat: 50, carbohydrate: 12, sodium: '3.5%' }, { name: 'Tahini', energy: 2760, protein: 25.0, fat: 57.3, carbohydrate: 12, sodium: '7.0%' }, { name: 'Butter Beans', energy: 384, protein: 7.4, fat: 0.9, carbohydrate: 15.2, sodium: '3.1%' }, { name: 'Chickpeas', energy: 391, protein: 5.0, fat: 34, carbohydrate: 5.5, sodium: '2.3%' }, { name: 'Lentils', energy: 290, protein: 4.2, fat: 0.9, carbohydrate: 15, sodium: '1.0%' } ], } }, } </script> TypeError: Cannot read property ‘width’ of undefined To get rid from the width undefined Vuetify error, we must define vuetify library to mounting function in main.js file as mentioned below. import Vue from 'vue' import App from './App.vue' import Vuetify from 'vuetify' import "vuetify/dist/vuetify.min.css"; Vue.use(Vuetify) new Vue({ vuetify: new Vuetify(), render: h => h(App) }).$mount('#app') Search DataTable in Vue Add a search prop to enable filtering feature in Data Tables is very easy in Vue with Vuetify.js. <template> <v-card> <v-card-title> Food Data <v-spacer></v-spacer> <v-text-field v-model="search" append-icon="mdi-magnify" label="Search" single-line hide-details ></v-text-field> </v-card-title> <v-data-table :headers="headers" :items="food" :search="search" ></v-data-table> </v-card> </template> <script> export default { data () { return { search: '', headers: [ { text: 'Food Items (Nutrition 100g)', align: 'start', sortable: false, value: 'name', }, { text: 'Energy', value: 'energy' }, { text: 'Protein', value: 'protein' }, { text: 'Fat', value: 'fat' }, { text: 'Carbohydrate', value: 'carbohydrate' }, { text: 'Sodium', value: 'sodium' }, ], food: [ { name: 'Muesli (Almond)', energy: 201, protein: 5.0, fat: 34, carbohydrate: 5.5, sodium: '1.5%' }, { name: 'Wholegrain Rolled Oats', energy: 301, protein: 3.0, fat: 54, carbohydrate: 3.5, sodium: '2.5%' }, { name: 'Almond Milk', energy: 130, protein: 6.0, fat: 24, carbohydrate: 3.9, sodium: '3.5%' }, { name: 'Firm Tofu', energy: 101, protein: 2.0, fat: 25, carbohydrate: 2.1, sodium: '0.5%' }, { name: 'Hummus', energy: 709, protein: 8.4, fat: 10.8, carbohydrate: 4.6, sodium: '2.5%' }, { name: 'Peanut Butter', energy: 2580, protein: 28, fat: 50, carbohydrate: 12, sodium: '3.5%' }, { name: 'Tahini', energy: 2760, protein: 25.0, fat: 57.3, carbohydrate: 12, sodium: '7.0%' }, { name: 'Butter Beans', energy: 384, protein: 7.4, fat: 0.9, carbohydrate: 15.2, sodium: '3.1%' }, { name: 'Chickpeas', energy: 391, protein: 5.0, fat: 34, carbohydrate: 5.5, sodium: '2.3%' }, { name: 'Lentils', energy: 290, protein: 4.2, fat: 0.9, carbohydrate: 15, sodium: '1.0%' } ], } }, } </script> i hope you like this article.