VueJS – AppDividend https://appdividend.com Latest Code Tutorials Wed, 20 Feb 2019 17:29:13 +0000 en-US hourly 1 https://wordpress.org/?v=5.0.3 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png VueJS – AppDividend https://appdividend.com 32 32 Vue Router Tutorial With Example | How To Use Routing in VueJS https://appdividend.com/2018/12/28/vue-router-tutorial-with-example-how-to-use-routing-in-vuejs/ https://appdividend.com/2018/12/28/vue-router-tutorial-with-example-how-to-use-routing-in-vuejs/#comments Fri, 28 Dec 2018 13:02:37 +0000 http://localhost/wordpress/?p=2950 Vue.js Router Tutorial With Example

Vue Router Tutorial With Example | How To Use Routing in VueJS is today’s topic. Vue is already an excellent Javascript library that allows you to create dynamic front-end applications. Vue.js is also great for single page applications (SPA).  Vue Router is the official router for Vue.js. It profoundly integrates with Vue.js core to make building Single […]

The post Vue Router Tutorial With Example | How To Use Routing in VueJS appeared first on AppDividend.

]]>
Vue.js Router Tutorial With Example

Vue Router Tutorial With Example | How To Use Routing in VueJS is today’s topic. Vue is already an excellent Javascript library that allows you to create dynamic front-end applications. Vue.js is also great for single page applications (SPA).  Vue Router is the official router for Vue.js. It profoundly integrates with Vue.js core to make building Single Page Applications with Vue.js a breeze. Features include:

  • Nested route/view mapping.
  • It is a modular, component-based router configuration.
  • Route params, query, wildcards.
  • View transition effects powered by Vue.js’ transition system.
  • It has a fine-grained navigation control.
  • It links with automatic active CSS classes.
  • It has HTML5 history mode or hash mode, with auto-fallback in IE9.
  • It has customizable Scroll Behavior.

In the JavaScript web application, the router is a part that syncs the currently displayed view with the browser address bar content. In other words, routing is the part that makes a URL change when you click something on a page and helps to show the correct view or HTML when you navigate the specific URL.

If you want to learn more about Vue.js then check out this Vue JS 2 – The Complete Guide (incl. Vue Router & Vuex) course.

Vue Router Tutorial With Example

First, we create the Vue project using Vue CLI. I have installed Vue CLI 3.0, and if you have not installed, then you can install by typing the following command.

sudo npm install -g @vue/cli

The above command needs to be executed on Administrator mode.

Then we can create a new project by typing the following command.

vue create vueroute

 

Vue Router Tutorial With Example | How To Use Routing in VueJS

Now, go inside the project.

cd vueroute

Step 1: Install Vue Router

Although, we can install the vue-router by default while we were creating a new project, let me install separately for you. So that we will integrate on our own.

npm install vue-router --save

I have installed the version 3.0.2 because, at this time, this is the latest version. You might be getting a different version from the future.

Now, you can import the router inside the Vue.js application. So let us import inside the src >> main.js file.

// main.js

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

Step 2: Basic Routing with Vue.js

Inside the src folder, create one file called routes.js and add the following code.

// routes.js

const routes = [];

export default routes;

In the future, we will define the routes inside this file. Now, we need to import this routes.js file inside the main.js file.

// main.js

import Vue from 'vue';
import App from './App.vue';
import VueRouter from 'vue-router';

import routes from './routes';

Vue.config.productionTip = false;

Vue.use(VueRouter);

new Vue({
  render: h => h(App),
  routes
}).$mount('#app');

So, we have passed the router object while creating a vue instance.

Step 3: Create Vue components

Next step is to create three new components inside the src >> components folder.

  1. Home.vue
  2. Register.vue
  3. Login.vue
// Home.vue

<template>
    <div>
        Home
    </div>
</template>
<script>
export default {
    
}
</script>
// Register.vue

<template>
    <div>
        Register
    </div>
</template>
<script>
export default {
    
}
</script>
// Login.vue

<template>
    <div>
        Login
    </div>
</template>
<script>
export default {
    
}
</script>

Now, import all the components inside src >> routes.js file. We will define the routes for each component.

// routes.js

import Home from './components/Home.vue';
import Register from './components/Register.vue';
import Login from './components/Login.vue';

const routes = [
    { path: '/', component: Home },
    { path: '/register', component: Register },
    { path: '/login', component: Login },
];

export default routes;

Next step is to create a VueRouter instance and pass the routes object. So, we need to import routes.js file inside the main.js file.

// main.js

import Vue from 'vue';
import App from './App.vue';
import VueRouter from 'vue-router';

import routes from './routes';

Vue.config.productionTip = false;

Vue.use(VueRouter);

const router = new VueRouter({routes});

new Vue({
    router,
    render: h => h(App)
}).$mount('#app');

Also, we need to display the routing components based on the routes. So we can do that by adding the <router-view> component. So let us add that inside src >> App.vue file.

// App.vue

<template>
  <div id="app">
    <nav>
        <router-link to='/'>Home</router-link>
        <router-link to='/register'>Register</router-link>
        <router-link to='/login'>Login</router-link>
    </nav>
    <router-view />
  </div>
</template>

<script>
export default {
}
</script>

Here, we have created basic navigation in which we have used the <router-link> to change the different component via navigation.

Save this file and go to the terminal and start the vue development server.

npm run serve

Now, go to the http://localhost:8080, and your URL changes to this: http://localhost:8080/# and it will render the Home component. 

We have used the Hash routing which is popular in building a Single Page Application(SPA).

Vue HTML 5 History Mode Routing

We are using hash mode of routing. We can also use HTML 5 History Mode. By default, vue.js uses the hash mode. We need to tell vue application externally to do the history routing.

We need to modify one line of code inside the main.js file, and we are done.

// main.js

const router = new VueRouter({mode: 'history', routes});

Now, we can be able to route the components without the hash.

Dynamic routing in Vue.js

The above example shows the different view based on the URL, handling the //register and routes.

We can achieve the dynamic segment. The above are were static segments.

Let us define one more route inside the src >> routes.js called /student/:id and also create a component inside the src >> components folder called Student.vue.

// Student.vue

<template>
    <div>
        Student
    </div>
</template>
<script>
export default {
    
}
</script>

Now, import the component inside the routes.js file and register that component.

// main.js

import Home from './components/Home.vue';
import Register from './components/Register.vue';
import Login from './components/Login.vue';
import Student from './components/Student.vue';

const routes = [
    { path: '/', component: Home },
    { path: '/register', component: Register },
    { path: '/login', component: Login },
    { path: '/student/:id', component: Student },
];

export default routes;

Here, in the above code, we have pass one parameter called id and that id is different for every student.

Now inside the student route component, we can reference the route using the $route and the access the id using $route.params.id. So, write the following code inside the Student.vue file.

// Student.vue

<template>
    <div>
        Student ID is: {{ $route.params.id }}
    </div>
</template>
<script>
export default {
    
}
</script>

We are using History mode routing. So go to the: http://localhost:8080/student/4 and now we can see that student id on our page. We can use this id parameter to load the contents from a backend. You can have as many dynamic segments as you want as per your requirement, in the same URL.

So, After you call Vue.use() method inside the main.js file,  passing the router object, in any component of the app you have access to these objects:

  1. this.$router:  which is the router object.
  2. this.$route:  which is the current route object.

Vue Router Object

We can access the router object using this.$router from any component when a Vue Router is installed in the root Vue component and it offers many nice features.

We can make the app navigate to a new route using

this.$router.push()
this.$router.replace()
this.$router.go()

If you have performed the CRUD operations previously using Vue.js as a frontend then we have used the push() method to change the route programmatically.

Named routes in Vue.js

We can simplify the linking process to navigating to different routes by defining the named routes or designated routes.

Sometimes it is more convenient to identify the route with the name, especially when linking to the route or performing navigations. You can give the route a name in the routes options while creating a Router instance. Now, we will add one property called name to the routes object in a routes.js file.

// routes.js

const routes = [
    { path: '/', component: Home, name: 'home' },
    { path: '/register', component: Register, name: 'register' },
    { path: '/login', component: Login, name: 'login' },
    { path: '/student/:id', component: Student, name: 'student' },
];

Now, we can change the links inside the navbar in App.vue file.

// App.vue

<template>
  <div id="app">
    <nav>
        <ul>
            <li>
                <router-link :to="{name: 'home'}">Home</router-link>
            </li>
            <li>
                <router-link :to="{name: 'register'}">Register</router-link>
            </li>
            <li>
                <router-link :to="{name: 'login'}">Login</router-link>
            </li>
            <li>
                <router-link :to="{name: 'student', params: {id: 2}}">Student</router-link>
            </li>
        </ul>
    </nav>
    <router-view />
  </div>
</template>

<script>
export default {
}
</script>

 

How To Use Routing in VueJS

Redirecting Programmatically in Vue Router

In the single page application, we often face a situation where we need to perform the redirecting after some operations are done successfully. We can redirect the route programmatically using the router object. For example, when the user successfully logged in, we need to redirect to the home route programmatically. Let us see the following example.

Let us create one more component called Redirect.vue inside the components folder and add the following code.

// Redirect.vue

<template>
    <div></div>
</template>
<script>
export default {
    mounted() {
        this.$router.push('/home');
    }
}
</script>

So, when the component is mounted, we will redirect the page to the Home component.

Import this component inside routes.js file and register.

// main.js

import Home from './components/Home.vue';
import Register from './components/Register.vue';
import Login from './components/Login.vue';
import Student from './components/Student.vue';
import Redirect from './components/Redirect.vue';

const routes = [
    { path: '/', component: Home, name: 'home' },
    { path: '/register', component: Register, name: 'register' },
    { path: '/login', component: Login, name: 'login' },
    { path: '/student/:id', component: Student, name: 'student' },
    { path: '/redirect', component: Redirect, name: 'redirect' },
];

export default routes;

Now, go to this URL: http://localhost:8080/redirect and see that we are redirecting to the Home component.

Navigating Router History with Go Method

Sometimes, we need to go forward and backward programmatically using navigating history routing. So, let us take an example of a 4o4 page. Let us create a component inside the components folder called 404.vue and add the following code.

// 404.vue

<template>
    <div>
        Whoops 404!! The page is not available.
        <a href="#" @click.prevent="back">Go back</a>
    </div>
</template>
<script>
export default {
    methods: {
        back() {
            this.$router.go(-1);
        }
    }
}
</script>

So, here, we have defined the 404 page and then put the link that will redirect to the previous route. Here, Inside the function, I have passed the -1 which means browser’s one step backward page from the browser and if we pass 1 then that means one page forward inside the browser.

Now, import inside the routes.js file.

// routes.js

import Home from './components/Home.vue';
import Register from './components/Register.vue';
import Login from './components/Login.vue';
import Student from './components/Student.vue';
import Redirect from './components/Redirect.vue';
import Error from './components/404.vue';

const routes = [
    { path: '/', component: Home, name: 'home' },
    { path: '/register', component: Register, name: 'register' },
    { path: '/login', component: Login, name: 'login' },
    { path: '/student/:id', component: Student, name: 'student' },
    { path: '/redirect', component: Redirect, name: 'redirect' },
    { path: '/404', component: Error, name: '404' },
];

export default routes;

Now, go to the http://localhost:8080/404, and you can see the link of the previous page. Click that link, and you will go to the last page. So it is working and programmatically.

Finally, Vue Router Tutorial With Example | How To Use Routing in VueJS is over.

The post Vue Router Tutorial With Example | How To Use Routing in VueJS appeared first on AppDividend.

]]>
https://appdividend.com/2018/12/28/vue-router-tutorial-with-example-how-to-use-routing-in-vuejs/feed/ 1
MEVN Stack Tutorial With Example From Scratch https://appdividend.com/2018/11/21/mevn-stack-tutorial-with-example-from-scratch/ https://appdividend.com/2018/11/21/mevn-stack-tutorial-with-example-from-scratch/#comments Wed, 21 Nov 2018 23:08:48 +0000 http://localhost/wordpress/?p=2278 MEVN Stack Tutorial Guide with Step by Step

MEVN Stack Tutorial With Example From Scratch is the topic, we will discuss today. We will generate FullStack Single Page Application(SPA) using MongoDB, Express, Vue, and Node.js CRUD Example Tutorial with step by step. For this example, we will not use Vuex for state management because this app will be simple and not complicated. We […]

The post MEVN Stack Tutorial With Example From Scratch appeared first on AppDividend.

]]>
MEVN Stack Tutorial Guide with Step by Step

MEVN Stack Tutorial With Example From Scratch is the topic, we will discuss today. We will generate FullStack Single Page Application(SPA) using MongoDB, Express, Vue, and Node.js CRUD Example Tutorial with step by step. For this example, we will not use Vuex for state management because this app will be simple and not complicated. We will create an application where the user can create, update, read, and delete the post. So, let us start the MEVN Stack Tutorial with an example.

If you want to learn more about Vue.js then check out this Vue JS 2 – The Complete Guide (incl. Vue Router & Vuex) course.

MEVN Stack Tutorial With Example From Scratch

We install Vue.js project using Vue CLI. Vue CLI requires the Node.js version 8.9 or above (8.11.0+ recommended). You can manage multiple versions of Node on the same machine with nvm or nvm-windows

Type the following command to install Vue CLI, if you have not installed.

npm install -g @vue/cli

# OR

yarn global add @vue/cli

You can check the version of Vue.js using this command.

vue --version

#1: Create a Vue.js project

Type the following command to install Vue.js.

vue create mevnexample

 

MEVN Stack Tutorial With Example From Scratch

Now, go inside the vue project.

cd mevnexample

Open the project inside code editor. I am using Visual Code.

code .

Start the vue dev server using the following command.

npm run serve

Go to the http://localhost:8080

You can see that we have successfully installed the Vue.js.

#2: Install Vue dependencies.

Type the following command to install the axiosvue-router and vue-axios dependencies. The vue-router is used for routing our Vue.js application to use the different components and the vue-axios for sending the network request to the server.

npm install axios vue-router vue-axios --save

Install the Bootstrap CSS Framework version 4 using the following command.

npm install bootstrap --save

Now, import the Bootstrap 4 CSS inside the main.js file.

// main.js

import Vue from 'vue'
import App from './App.vue'
import 'bootstrap/dist/css/bootstrap.min.css'

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')

#3: Create the vue components.

Go to the src >> components folder and remove the HelloWorld.vue file and create the following components.

  1. HomeComponent.vue
  2. CreateComponent.vue
  3. EditComponent.vue
  4. IndexComponent.vue

Now, add the following code inside the HomeComponent.vue file.

<template>
  <div class="row justify-content-center">
      <div class="col-md-8">
          <div class="card card-default">
              <div class="card-header">Home Component</div>

              <div class="card-body">
                  I'm the Home Component component.
              </div>
          </div>
      </div>
  </div>
</template>
<script>
export default {
}
</script>

Next step is to import the HomeComponent.vue file inside the App.vue file.

// App.vue

<template>
  <div>
    <HomeComponent />
  </div>
</template>

<script>
import HomeComponent from './components/HomeComponent.vue'

export default {
  name: 'app',
  components: {
    HomeComponent
  }
}
</script>

Save the file, and if the server is running, then you can go to the http://localhost:8080 and see that HomeComponent is rendering.

Now, create the remaining three components.

// CreateComponent.vue

<template>
  <div class="row justify-content-center">
      <div class="col-md-8">
          <div class="card card-default">
              <div class="card-header">Create Component</div>

              <div class="card-body">
                  I'm the Create Component component.
              </div>
          </div>
      </div>
  </div>
</template>

<script>
  export default {
  }
</script>
// EditComponent.vue

<template>
  <div class="row justify-content-center">
      <div class="col-md-8">
          <div class="card card-default">
              <div class="card-header">Edit Component</div>

              <div class="card-body">
                  I'm an Edit component.
              </div>
          </div>
      </div>
  </div>
</template>

<script>
  export default {
  }
</script>
// IndexComponent.vue

<template>
  <div class="row justify-content-center">
      <div class="col-md-8">
          <div class="card card-default">
              <div class="card-header">Index Component</div>

              <div class="card-body">
                  I'm an Index component.
              </div>
          </div>
      </div>
  </div>
</template>

<script>
  export default {
  }
</script>

#4: Configure the vue-router

Inside the main.js file, write the following code.

// main.js

import Vue from 'vue'
import App from './App.vue'
import 'bootstrap/dist/css/bootstrap.min.css'

import VueRouter from 'vue-router';
Vue.use(VueRouter);

Vue.config.productionTip = false;

import HomeComponent from './components/HomeComponent.vue';
import CreateComponent from './components/CreateComponent.vue';
import IndexComponent from './components/IndexComponent.vue';
import EditComponent from './components/EditComponent.vue';

const routes = [
  {
      name: 'home',
      path: '/',
      component: HomeComponent
  },
  {
      name: 'create',
      path: '/create',
      component: CreateComponent
  },
  {
      name: 'posts',
      path: '/posts',
      component: IndexComponent
  },
  {
      name: 'edit',
      path: '/edit/:id',
      component: EditComponent
  }
];

const router = new VueRouter({ mode: 'history', routes: routes});

new Vue(Vue.util.extend({ router }, App)).$mount('#app');

What we have done is that, first, imported the vue-router module and then create an array of routes which has a name, path, and components as the properties.

Then we have created the router object and passed the mode history and the routes array. So when the application boot, we will give these routes to the vue application.

Now, the next step is to define the <router-view></router-view> element. It renders the component according to the routing path in the Vue application.

So, add the <router-view> inside the App.vue file.

// App.vue

<template>
  <div>
    <router-view></router-view>
  </div>
</template>

<script>


export default {
  name: 'app'
}
</script>

Save the file and check the following route paths to see if we are getting the exact routes.

  1. http://localhost:8080/create
  2. http://localhost:8080/posts
  3. http://localhost:8080/edit/21

#5: Create a Navigation bar

Write the following code inside the App.vue file. I have added the navbar.

// App.vue

<template>
  <div class="container">
    <nav class="navbar navbar-expand-sm bg-dark navbar-dark">
      <ul class="navbar-nav">
        <li class="nav-item">
          <router-link to="/" class="nav-link">Home</router-link>
        </li>
        <li class="nav-item">
          <router-link to="/create" class="nav-link">Create Post</router-link>
        </li>
        <li class="nav-item">
          <router-link to="/posts" class="nav-link">Posts</router-link>
        </li>
      </ul>
    </nav><br />
    <transition name="fade">
      <router-view></router-view>
    </transition>
  </div>
</template>

<style>
    .fade-enter-active, .fade-leave-active {
      transition: opacity .5s
    }
    .fade-enter, .fade-leave-active {
      opacity: 0
    }
</style>

<script>

    export default{
    }
</script>

So, what we have done is that add the navigation bar and add some animation effect like transition. So when we navigate the routes, the component is changing according to their path.

 

Vue Node CRUD Example

#6: Create a Form

We need to create a form to enter the details of form. So let us create a form inside the CreateComponent.vue file.

// CreateComponent.vue

<template>
  <div>
    <h1>Create A Post</h1>
    <form @submit.prevent="addPost">
      <div class="row">
        <div class="col-md-6">
          <div class="form-group">
            <label>Post Title:</label>
            <input type="text" class="form-control" v-model="post.title">
          </div>
        </div>
        </div>
        <div class="row">
          <div class="col-md-6">
            <div class="form-group">
              <label>Post Body:</label>
              <textarea class="form-control" v-model="post.body" rows="5"></textarea>
            </div>
          </div>
        </div><br />
        <div class="form-group">
          <button class="btn btn-primary">Create</button>
        </div>
    </form>
  </div>
</template>

<script>
    export default {
        data(){
        return {
          post:{}
        }
    },
    methods: {
      addPost(){
        console.log(this.post);
      }
    }
  }
</script>

Also, we have defined the object called post. So here, we have used the two-way data binding. The post object has two properties. 1) title 2) body.

We have made one method called addPost().  So, when a user submits the form, we will get the input inside the addPost() method. From then, we will send a POST request to the Laravel server and to save the data into the database.

I am skipping the validation of each field because this article is getting long and long. So we will do it in another post.

Save the file and go to this URL: http://localhost:8080/create or /create. You can see the form like below.

 

Vue Express CRUD Tutorial Example

#7: Create a Node.js backend.

Create one folder inside the vue project root called api and go inside that folder.

Now, initialize the package.json file.

npm init -y

Now, install the following node.js dependencies. 

yarn add express body-parser cors mongoose

# or

npm install express body-parser cors mongoose --save

Also, install a nodemon server as a development dependency. So that we do not need to restart every time, we change our server code.

We have installed the express web framework which is built on top of the Node.js server. Also, installed the body-parser module to parse the data coming from the request and then installed the cors module which will help us to ignore the cross-site request origin warning from the browser. It is security provided by the browser when we request them from a different server.

npm install nodemon --save-dev

Now create three files called server.js, DB.js, post.model.js, and post.route.js. All these files are inside the root of the api folder. Write the following code in the server.js file.

// server.js

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const PORT = 4000;
const cors = require('cors');

app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.listen(PORT, function(){
  console.log('Server is running on Port:',PORT);
});

Now, we need to start a node server using the following command.

nodemon server

So, our node.js server is running at port: 4000

 

Vue Node Tutorial Example

#8: Setup and connect MongoDB database.

If you are the beginner in the MongoDB database, then please check out my below tutorial.

Related Post: NoSQL MongoDB Tutorial

I have already installed the MongoDB on Mac. So I am starting the MongoDB server by the following command. You can also use any MongoDB, database client. I am just using the terminal for this demo because it is a simple application.

mongod

Inside an api folder, create one file called the DB.js which is responsible for connecting our node application to the mongodb database. So add the following line of code.

// DB.js

module.exports = {
    DB: 'mongodb://localhost:27017/mevncrud'
}

In my local MongoDB database, username and password are empty, but in the production database, you need to create one user and assign that user to the database

Now, import this DB.js file into the server.js file.

// server.js

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const PORT = 4000;
const cors = require('cors');
const mongoose = require('mongoose');
const config = require('./DB.js');

mongoose.Promise = global.Promise;
mongoose.connect(config.DB, { useNewUrlParser: true }).then(
  () => {console.log('Database is connected') },
  err => { console.log('Can not connect to the database'+ err)}
);

app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.listen(PORT, function(){
  console.log('Server is running on Port:',PORT);
});

Save the file, and you can see inside the terminal that our node.js application is connected to the mongodb database.

#9: Create a Mongoose Schema

Write the following code inside the post.model.js file.

// post.model.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Define collection and schema for Post
let Post = new Schema({
  title: {
    type: String
  },
  body: {
    type: String
  }
},{
    collection: 'posts'
});

module.exports = mongoose.model('Post', Post);

We have taken three fields called title and body with String datatype.

#10: Define a route for Node.js Express application

Write the CRUD operation code inside the post.route.js file.

// post.model.js

const express = require('express');
const postRoutes = express.Router();

// Require Post model in our routes module
let Post = require('./post.model');

// Defined store route
postRoutes.route('/add').post(function (req, res) {
  let post = new Post(req.body);
  post.save()
    .then(() => {
      res.status(200).json({'business': 'business in added successfully'});
    })
    .catch(() => {
      res.status(400).send("unable to save to database");
    });
});

// Defined get data(index or listing) route
postRoutes.route('/').get(function (req, res) {
    Post.find(function(err, posts){
    if(err){
      res.json(err);
    }
    else {
      res.json(posts);
    }
  });
});

// Defined edit route
postRoutes.route('/edit/:id').get(function (req, res) {
  let id = req.params.id;
  Post.findById(id, function (err, post){
      if(err) {
        res.json(err);
      }
      res.json(post);
  });
});

//  Defined update route
postRoutes.route('/update/:id').post(function (req, res) {
    Post.findById(req.params.id, function(err, post) {
    if (!post)
      res.status(404).send("data is not found");
    else {
        post.title = req.body.title;
        post.body = req.body.body;
        post.save().then(() => {
          res.json('Update complete');
      })
      .catch(() => {
            res.status(400).send("unable to update the database");
      });
    }
  });
});

// Defined delete | remove | destroy route
postRoutes.route('/delete/:id').delete(function (req, res) {
    Post.findByIdAndRemove({_id: req.params.id}, function(err){
        if(err) res.json(err);
        else res.json('Successfully removed');
    });
});

module.exports = postRoutes;

Here, we have defined the CRUD operations in Node.js, which is backend server side. So when the request from the clientside hits the node express server, it maps the URI and according to URI, the above function will be executed, and database operation will be performed and send the response to the client, and in our case, it is vue.js frontend.

Here, we have used a Mongoose ORM to create, read, update, delete the data from the mongodb databaseMongoose is an ORM(Object Relational Mapping) used in the MongoDB database. Now, we have all the CRUD operations set up on the post.route.js file; we need to import inside the server.js file.

So, our final server.js file looks like this.

// server.js

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const PORT = 4000;
const cors = require('cors');
const mongoose = require('mongoose');
const config = require('./DB.js');
const postRoute = require('./post.route');

mongoose.Promise = global.Promise;
mongoose.connect(config.DB, { useNewUrlParser: true }).then(
  () => { console.log('Database is connected') },
  err => { console.log('Can not connect to the database'+ err)}
);

app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.use('/posts', postRoute);

app.listen(PORT, function(){
  console.log('Server is running on Port:',PORT);
});
If the linter is showing error on console statement inside the Visual Studio Code editor or other editors, then ignore it because it is warning provided by eslint configuration. It is not an actual error and you can able to see the output inside the browser.

#11: Use axios to send a network request

Go to the frontend vue project and import the axios and vue-axios inside the main.js file.

// main.js

import Vue from 'vue'
import App from './App.vue'
import 'bootstrap/dist/css/bootstrap.min.css'

import VueRouter from 'vue-router';
Vue.use(VueRouter);

import VueAxios from 'vue-axios';
import axios from 'axios';

Vue.use(VueAxios, axios);

Vue.config.productionTip = false;

import HomeComponent from './components/HomeComponent.vue';
import CreateComponent from './components/CreateComponent.vue';
import IndexComponent from './components/IndexComponent.vue';
import EditComponent from './components/EditComponent.vue';

const routes = [
  {
      name: 'home',
      path: '/',
      component: HomeComponent
  },
  {
      name: 'create',
      path: '/create',
      component: CreateComponent
  },
  {
      name: 'posts',
      path: '/posts',
      component: IndexComponent
  },
  {
      name: 'edit',
      path: '/edit/:id',
      component: EditComponent
  }
];

const router = new VueRouter({ mode: 'history', routes: routes});

new Vue(Vue.util.extend({ router }, App)).$mount('#app');

Now, we have created the backend. Next step is to send the POST request to the node.js api server. Remember, now we have now three servers are running.

  1. Vue development server
  2. Node.js server
  3. MongoDB server

Remember, all are running fine otherwise the project won’t work.

Write the following code inside the CreateComponent.vue file’s addPost() function.

// CreateComponent.vue

addPost(){
    let uri = 'http://localhost:4000/posts/add';
    this.axios.post(uri, this.post).then(() => {
       this.$router.push({name: 'posts'});
    });
}

You can now create the post and see in the mongodb database.

To check from the terminal, you need to open the mongoshell using the following command.

mongo

 

MongoDB database example

#12: Display the backend data

Write the following code inside the IndexComponent.js file.

// IndexComponent.js

<template>
  <div>
      <h1>Posts</h1>
        <div class="row">
          <div class="col-md-10"></div>
          <div class="col-md-2">
            <router-link :to="{ name: 'create' }" class="btn btn-primary">Create Post</router-link>
          </div>
        </div><br />

        <table class="table table-hover">
            <thead>
            <tr>
              <th>Title</th>
              <th>Body</th>
              <th>Actions</th>
            </tr>
            </thead>
            <tbody>
                <tr v-for="post in posts" :key="post._id">
                  <td>{{ post.title }}</td>
                  <td>{{ post.body }}</td>
                  <td><router-link :to="{name: 'edit', params: { id: post._id }}" class="btn btn-primary">Edit</router-link></td>
                  <td><button class="btn btn-danger">Delete</button></td>
                </tr>
            </tbody>
        </table>
  </div>
</template>

<script>
  export default {
      data() {
        return {
          posts: []
        }
      },
      created() {
      let uri = 'http://localhost:4000/posts';
      this.axios.get(uri).then(response => {
        this.posts = response.data;
      });
    }
  }
</script>

When the component is created, it will send a GET request to the node.js server and fetch the data from the database and then assign that data to the posts array, and then we loop through that array and display the data in the tabular format.

MEVN CRUD Example

 

#13: Send edit and update request

Now, when our edit component loads, we need to fetch the data from the server to display the existing data.

Then, after changing the data in the textbox and textarea, we hit the update button, and we call the updatePost() function to send a post request to the server to update the data.

// EditComponent.vue

<template>
  <div>
    <h1>Edit Post</h1>
    <form @submit.prevent="updatePost">
      <div class="row">
        <div class="col-md-6">
          <div class="form-group">
            <label>Post Title:</label>
            <input type="text" class="form-control" v-model="post.title">
          </div>
        </div>
        </div>
        <div class="row">
          <div class="col-md-6">
            <div class="form-group">
              <label>Post Body:</label>
              <textarea class="form-control" v-model="post.body" rows="5"></textarea>
            </div>
          </div>
        </div><br />
        <div class="form-group">
          <button class="btn btn-primary">Update</button>
        </div>
    </form>
  </div>
</template>

<script>
    export default {

      data() {
        return {
          post: {}
        }
      },
      created() {
        let uri = `http://localhost:4000/posts/edit/${this.$route.params.id}`;
        this.axios.get(uri).then((response) => {
            this.post = response.data;
        });
      },
      methods: {
        updatePost() {
          let uri = `http://localhost:4000/posts/update/${this.$route.params.id}`;
          this.axios.post(uri, this.post).then(() => {
            this.$router.push({name: 'posts'});
          });
        }
      }
    }
</script>

You will see the edit data from the database and also you can update the database. So till now, insert, read,  and update operations are complete. Now, last, the delete is remaining.

#14: Delete or Remove the data.

Now, the only remaining thing is to delete or remove the data from the database.

So, let us write the final code inside the IndexComponent.vue file.

// IndexComponent.vue

<template>
  <div>
      <h1>Posts</h1>
        <div class="row">
          <div class="col-md-10"></div>
          <div class="col-md-2">
            <router-link :to="{ name: 'create' }" class="btn btn-primary">Create Post</router-link>
          </div>
        </div><br />

        <table class="table table-hover">
            <thead>
            <tr>
              <th>Title</th>
              <th>Body</th>
              <th>Actions</th>
            </tr>
            </thead>
            <tbody>
                <tr v-for="post in posts" :key="post._id">
                  <td>{{ post.title }}</td>
                  <td>{{ post.body }}</td>
                  <td><router-link :to="{name: 'edit', params: { id: post._id }}" class="btn btn-primary">Edit</router-link></td>
                  <td><button class="btn btn-danger" @click.prevent="deletePost(post._id)">Delete</button></td>
                </tr>
            </tbody>
        </table>
  </div>
</template>

<script>
  export default {
      data() {
        return {
          posts: []
        }
      },
      created() {
      let uri = 'http://localhost:4000/posts';
      this.axios.get(uri).then(response => {
        this.posts = response.data;
      });
    },
    methods: {
      deletePost(id)
      {
        let uri = `http://localhost:4000/posts/delete/${id}`;
        this.axios.delete(uri).then(response => {
          this.posts.splice(this.posts.indexOf(id), 1);
        });
      }
    }
  }
</script>

Save the file, and now, you can also delete the values from the MongoDB database.

So, finally, our MEVN Stack Tutorial With Example Demo is over. I have put this code on Github. So check that out as well.

Github Code

Steps to use code

  1. Clone the repository.
  2. Go inside the vue project and type this command: npm install
  3. Go inside the api folder and type this command: npm install
  4. Now, start the mongodb server.
  5. Also, start the node server using this command: nodemon server
  6. Go to the vue root project and type this command: npm run serve
  7. Go to the http://localhost:8080 and your project is running.

The post MEVN Stack Tutorial With Example From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2018/11/21/mevn-stack-tutorial-with-example-from-scratch/feed/ 4
Vue Laravel CRUD Example Tutorial From Scratch https://appdividend.com/2018/11/17/vue-laravel-crud-example-tutorial-from-scratch/ https://appdividend.com/2018/11/17/vue-laravel-crud-example-tutorial-from-scratch/#comments Sat, 17 Nov 2018 12:06:50 +0000 http://localhost/wordpress/?p=2210 Laravel Vue CRUD Tutorial With Example

Vue Laravel CRUD Example Tutorial From Scratch is today’s leading topic.  Laravel is the PHP’s fastest growing Framework with scalability and flexibility. VueJS is the fastest growing Front end Library in the Javascript community. Laravel is providing VueJS support out of the box.  For this demo, we will not create separate projects for the frontend because Laravel provides the best support for Vue.js. So, we will […]

The post Vue Laravel CRUD Example Tutorial From Scratch appeared first on AppDividend.

]]>
Laravel Vue CRUD Tutorial With Example

Vue Laravel CRUD Example Tutorial From Scratch is today’s leading topic.  Laravel is the PHP’s fastest growing Framework with scalability and flexibility. VueJS is the fastest growing Front end Library in the Javascript community. Laravel is providing VueJS support out of the box.  For this demo, we will not create separate projects for the frontend because Laravel provides the best support for Vue.js. So, we will build the Vue components inside the Laravel’s assets folder.

We will create a Single Page Application(SPA) using the Laravel and Vue.js. In this SPA, you can create a post, edit the post, read the post and delete the post. We will create Laravel API Backend.

If you want to learn more about Vue.js then check out this Vue JS 2 – The Complete Guide (incl. Vue Router & Vuex) course.

Vue Laravel CRUD Example Tutorial

Now, first, we need to install the Laravel application. So let us install new Laravel by the following command.

#1: Install Laravel 5.7

laravel new vuelaravelcrud

 

Vue Laravel CRUD Example Tutorial

Now, go inside the project folder and install the frontend dependencies using the following command.

npm install

Also, open the project in your editor. I am using Visual Studio Code.

code .

Setup the database configuration inside the .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=vuecrud
DB_USERNAME=root
DB_PASSWORD=root

Save the file, and now your backend can connect the MySQL database. 

Now, start the compiling assets using the following command.

npm run dev

 

Laravel Vue CRUD Example

We can also run the following command to compile the assets as you write the new code or modify the existing code.

npm run watch

#2: Install Vue dependency and edit configurations.

Type the following command to install the vue-router and vue-axios dependencies. The vue-router is used for routing our Vue.js application to use the different components and the vue-axios for sending the network request to the server.

npm install vue-router vue-axios --save

Now, we need to change the app.js file inside resources  >> js folder.

Modify with the following code inside the app.js file.

// App.js

require('./bootstrap');

window.Vue = require('vue');

import VueRouter from 'vue-router';
Vue.use(VueRouter);

import VueAxios from 'vue-axios';
import axios from 'axios';
Vue.use(VueAxios, axios);

Vue.component('example-component', require('./components/ExampleComponent.vue'));

const router = new VueRouter({ mode: 'history'});
const app = new Vue(Vue.util.extend({ router })).$mount('#app');

Here, we have configured the vue-router and vue-axios library.

Now, inside the resources >> views folder, create one file called the post.blade.php file.

Add the following code inside the post.blade.php file.

<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel</title>
        <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet" type="text/css">
        <link href="{{ mix('css/app.css') }}" type="text/css" rel="stylesheet" />
        <meta name="csrf-token" value="{{ csrf_token() }}" />
    </head>
    <body>
        <div id="app">
          <example-component></example-component>
        </div>
        <script src="{{ mix('js/app.js') }}" type="text/javascript"></script>
    </body>
</html>

Now, change the route inside the routes >> web.php file. We are building the Single Page Application using Laravel and Vue. So we need to define the following route, where we can push any route and then it will give the correct route without any error. Otherwise, it will give the 404 error because, in Laravel, you have not defined any route, it is the Vue where you have defined the various component route.

Due to the following code, now you can be able to use Laravel route proxy as a Vue route, and you can display the Vue components depending on the current URL.

<?php

Route::get('/{any}', function () {
  return view('post');
})->where('any', '.*');

Save the file and go to the browser and see the result. You can see that we have successfully integrated the Vue component in our Laravel application.

#3: Create Vue Components

Inside the resources >>  js folder, create a folder called components and inside that folder, create four following vue components.

  1. HomeComponent.vue
  2. CreateComponent.vue
  3. EditComponent.vue
  4. IndexComponent.vue
// HomeComponent.vue

<template>
  <div class="row justify-content-center">
      <div class="col-md-8">
          <div class="card card-default">
              <div class="card-header">Home Component</div>

              <div class="card-body">
                  I'm the Home Component component.
              </div>
          </div>
      </div>
  </div>
</template>

<script>
    export default {
        mounted() {
            console.log('Component mounted.')
        }
    }
</script>
// CreateComponent.vue

<template>
  <div class="row justify-content-center">
      <div class="col-md-8">
          <div class="card card-default">
              <div class="card-header">Create Component</div>

              <div class="card-body">
                  I'm the Create Component component.
              </div>
          </div>
      </div>
  </div>
</template>

<script>
    export default {
        mounted() {
            console.log('Component mounted.')
        }
    }
</script>
// EditComponent.vue

<template>
  <div class="row justify-content-center">
      <div class="col-md-8">
          <div class="card card-default">
              <div class="card-header">Edit Component</div>

              <div class="card-body">
                  I'm an Edit component.
              </div>
          </div>
      </div>
  </div>
</template>

<script>
    export default {
        mounted() {
            console.log('Example Component mounted.')
        }
    }
</script>
// IndexComponent.vue

<template>
  <div class="row justify-content-center">
      <div class="col-md-8">
          <div class="card card-default">
              <div class="card-header">Index Component</div>

              <div class="card-body">
                  I'm an Index component.
              </div>
          </div>
      </div>
  </div>
</template>

<script>
    export default {
        mounted() {
            console.log('Index Component mounted.')
        }
    }
</script>

#4: Configure the vue-router

Inside the app.js file, write the following code.

// app.js

require('./bootstrap');

window.Vue = require('vue');

import VueRouter from 'vue-router';
Vue.use(VueRouter);

import VueAxios from 'vue-axios';
import axios from 'axios';

import App from './App.vue';
Vue.use(VueAxios, axios);

import HomeComponent from './components/HomeComponent.vue';
import CreateComponent from './components/CreateComponent.vue';
import IndexComponent from './components/IndexComponent.vue';
import EditComponent from './components/EditComponent.vue';

const routes = [
  {
      name: 'home',
      path: '/',
      component: HomeComponent
  },
  {
      name: 'create',
      path: '/create',
      component: CreateComponent
  },
  {
      name: 'posts',
      path: '/posts',
      component: IndexComponent
  },
  {
      name: 'edit',
      path: '/edit/:id',
      component: EditComponent
  }
];

const router = new VueRouter({ mode: 'history', routes: routes});
const app = new Vue(Vue.util.extend({ router }, App)).$mount('#app');

Here, we have imported the four components and also defined the routes for our application. Then we have created a router object and passed it to our Vue application.

Now, create one more vue component inside the resources >> js folder called App.vue and add the following code in it.

// App.vue

<template>
    <div class="container">
        <div>
            <transition name="fade">
                <router-view></router-view>
            </transition>
        </div>
    </div>
</template>

<style>
    .fade-enter-active, .fade-leave-active {
      transition: opacity .5s
    }
    .fade-enter, .fade-leave-active {
      opacity: 0
    }
</style>

<script>

    export default{
    }
</script>

Here, we have defined our router- view. It is the directive that will render the component according to current URL. So, if our URL is /create, then it will present the CreateComponent on the webpage.

Save the file, and if your npm run watch is not running, then you might need to compile again and then go to the browser and go to these URLs for testing and see if the project is working or not.

  1. http://vuelaravelcrud.test/create
  2. http://vuelaravelcrud.test/posts
  3. http://vuelaravelcrud.test/edit/21

If you are getting the exact component, then you are perfectly fine and if not then check out for the error on the terminal as well as the console panel in the browser.

#5: Create a Navigation bar

Write the following code inside the App.vue file. I have added the navbar.

// App.vue

<template>
  <div class="container">
    <nav class="navbar navbar-expand-sm bg-dark navbar-dark">
      <ul class="navbar-nav">
        <li class="nav-item">
          <router-link to="/" class="nav-link">Home</router-link>
        </li>
        <li class="nav-item">
          <router-link to="/create" class="nav-link">Create Post</router-link>
        </li>
        <li class="nav-item">
          <router-link to="/posts" class="nav-link">Posts</router-link>
        </li>
      </ul>
    </nav><br />
    <transition name="fade">
      <router-view></router-view>
    </transition>
  </div>
</template>

<style>
    .fade-enter-active, .fade-leave-active {
      transition: opacity .5s
    }
    .fade-enter, .fade-leave-active {
      opacity: 0
    }
</style>

<script>

    export default{
    }
</script>

Save the file and see the output on the browser.

 

Laravel Vue Tutorial

#6: Create a Form

Write the following code inside the CreateComponent.vue file. We will add the Bootstrap Form to create a post.

// CreatePost.vue

<template>
  <div>
    <h1>Create A Post</h1>
    <form @submit.prevent="addPost">
      <div class="row">
        <div class="col-md-6">
          <div class="form-group">
            <label>Post Title:</label>
            <input type="text" class="form-control" v-model="post.title">
          </div>
        </div>
        </div>
        <div class="row">
          <div class="col-md-6">
            <div class="form-group">
              <label>Post Body:</label>
              <textarea class="form-control" v-model="post.body" rows="5"></textarea>
            </div>
          </div>
        </div><br />
        <div class="form-group">
          <button class="btn btn-primary">Create</button>
        </div>
    </form>
  </div>
</template>

<script>
    export default {
        data(){
        return {
          post:{}
        }
    },
    methods: {
      addPost(){
        console.log(this.post);
      }
    }
  }
</script>

So, we have taken the two fields. Post Title and Post Body. We have made one method called addPost().  So, when a user submits the form, we will get the input inside the addPost() method. From then, we will send a POST request to the Laravel server and to save the data into the database.

I am skipping the validation of each field because this article is getting long and long. So we will do it in another post.

Save the file and go to this URL: http://vuelaravelcrud.test/create or /create. You can see the form like below.

 

Laravel Vue Example

#7: Create a Laravel Backend

The primary purpose of the Laravel Framework in this example is to build a backend API. So, first, we will create a schema for post table. Also, we need a Post model. So let’s create both using the following command.

php artisan make:model Post -m

Now, write the following schema inside [timestamp]create_posts_table.php file.

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
       $table->increments('id');
       $table->string('title');
       $table->text('body');
       $table->timestamps();
    });
}

Migrate the database using the following command.

php artisan migrate

Next, inside the Post.php model, write the following code to prevent the mass assignment exception.

<?php

// Post.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = ['title', 'body'];
}

Also, create a controller using the following command.

php artisan make:controller PostController

We are using Laravel Resource Collection for API development. So let us create a Laravel Resource Collection using the following command.

php artisan make:resource PostCollection

When building an API, you may need a transformation layer that sits between your Eloquent models and the JSON responses that are returned to your application’s users. Laravel’s resource classes allow you to expressively and quickly transform your models and model collections into JSON.

The PostCollection resource is generated inside app >> Http >>Resources >> PostCollection.php file.

<?php

// PostCollection.php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;

class PostCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return parent::toArray($request);
    }
}

#8: Define the CRUD operations

First, we define the function that stores the data inside the MySQL database.

<?php

// PostController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Resources\PostCollection;
use App\Post;

class PostController extends Controller
{
    public function store(Request $request)
    {
      $post = new Post([
        'title' => $request->get('title'),
        'body' => $request->get('body')
      ]);

      $post->save();

      return response()->json('success');
    }
}

Now, write the edit, update, index, and delete functions as well.

<?php

// PostController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Resources\PostCollection;
use App\Post;

class PostController extends Controller
{
    public function store(Request $request)
    {
      $post = new Post([
        'title' => $request->get('title'),
        'body' => $request->get('body')
      ]);

      $post->save();

      return response()->json('successfully added');
    }

    public function index()
    {
      return new PostCollection(Post::all());
    }

    public function edit($id)
    {
      $post = Post::find($id);
      return response()->json($post);
    }

    public function update($id, Request $request)
    {
      $post = Post::find($id);

      $post->update($request->all());

      return response()->json('successfully updated');
    }

    public function delete($id)
    {
      $post = Post::find($id);

      $post->delete();

      return response()->json('successfully deleted');
    }
}

#9: Define the api routes

Now, we need to define the API routes inside the routes >> api.php file.

<?php

// api.php

use Illuminate\Http\Request;

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::post('/post/create', 'PostController@store');
Route::get('/post/edit/{id}', 'PostController@edit');
Route::post('/post/update/{id}', 'PostController@update');
Route::delete('/post/delete/{id}', 'PostController@delete');
Route::get('/posts', 'PostController@index');

#10: Use Axios to send a network request

Now, we have created the backend. Next step is to send a POST request to the Laravel development server.

Write the following code inside the CreateComponent.vue file’s addPost() function.

// CreateComponent.vue

addPost(){
    let uri = 'http://vuelaravelcrud.test/api/post/create';
    this.axios.post(uri, this.post).then((response) => {
       this.$router.push({name: 'posts'});
    });
}

So, it will post a request to the server’s api point with the data and the server saves the data.

Now, display the posts. So let us edit the IndexComponent.vue file.

// IndexComponent.vue

<template>
  <div>
      <h1>Posts</h1>
        <div class="row">
          <div class="col-md-10"></div>
          <div class="col-md-2">
            <router-link :to="{ name: 'create' }" class="btn btn-primary">Create Post</router-link>
          </div>
        </div><br />

        <table class="table table-hover">
            <thead>
            <tr>
                <th>ID</th>
                <th>Item Name</th>
                <th>Item Price</th>
                <th>Actions</th>
            </tr>
            </thead>
            <tbody>
                <tr v-for="post in posts" :key="post.id">
                    <td>{{ post.id }}</td>
                    <td>{{ post.title }}</td>
                    <td>{{ post.body }}</td>
                    <td><router-link :to="{name: 'edit', params: { id: post.id }}" class="btn btn-primary">Edit</router-link></td>
                    <td><button class="btn btn-danger">Delete</button></td>
                </tr>
            </tbody>
        </table>
  </div>
</template>

<script>
  export default {
      data() {
        return {
          posts: []
        }
      },
      created() {
      let uri = 'http://vuelaravelcrud.test/api/posts';
      this.axios.get(uri).then(response => {
        this.posts = response.data.data;
      });
    }
  }
</script>

Here, when the component is created, we send the network request to fetch the data.

Now, here, we need to write the data because axios is by default wrap our backend data posts with data and we are using the Resource Collection. So it will also wrap the data in the data key. So to get the actual data, we need to write like response.data.data. If we have not used axios then we might write the response.data, but axios also has backend data template like response.data, and that is why we need to write the response.data.data.

#11: Send edit and update request

Now, when our edit component loads, we need to fetch the data from the server to display the existing data.

Then, after changing the data in the textbox and textarea, we hit the update button and we call the updatePost() function to send a post request to the server to update the data.

// EditComponent.vue

<template>
  <div>
    <h1>Edit Post</h1>
    <form @submit.prevent="updatePost">
      <div class="row">
        <div class="col-md-6">
          <div class="form-group">
            <label>Post Title:</label>
            <input type="text" class="form-control" v-model="post.title">
          </div>
        </div>
        </div>
        <div class="row">
          <div class="col-md-6">
            <div class="form-group">
              <label>Post Body:</label>
              <textarea class="form-control" v-model="post.body" rows="5"></textarea>
            </div>
          </div>
        </div><br />
        <div class="form-group">
          <button class="btn btn-primary">Update</button>
        </div>
    </form>
  </div>
</template>

<script>
    export default {

      data() {
        return {
          post: {}
        }
      },
      created() {
        let uri = `http://vuelaravelcrud.test/api/post/edit/${this.$route.params.id}`;
        this.axios.get(uri).then((response) => {
            this.post = response.data;
        });
      },
      methods: {
        updatePost() {
          let uri = `http://vuelaravelcrud.test/api/post/update/${this.$route.params.id}`;
          this.axios.post(uri, this.post).then((response) => {
            this.$router.push({name: 'posts'});
          });
        }
      }
    }
</script>

Now, you can try to edit the data and update the form, and you can see that we can now update the data.

#12: Delete the data

Now, the only remaining thing is to delete or remove the data from the database.

So, let us write the final code inside the IndexComponent.vue file.

// IndexComponent.vue

<template>
  <div>
      <h1>Posts</h1>
        <div class="row">
          <div class="col-md-10"></div>
          <div class="col-md-2">
            <router-link :to="{ name: 'create' }" class="btn btn-primary">Create Post</router-link>
          </div>
        </div><br />

        <table class="table table-hover">
            <thead>
            <tr>
                <th>ID</th>
                <th>Item Name</th>
                <th>Item Price</th>
                <th>Actions</th>
            </tr>
            </thead>
            <tbody>
                <tr v-for="post in posts" :key="post.id">
                    <td>{{ post.id }}</td>
                    <td>{{ post.title }}</td>
                    <td>{{ post.body }}</td>
                    <td><router-link :to="{name: 'edit', params: { id: post.id }}" class="btn btn-primary">Edit</router-link></td>
                    <td><button class="btn btn-danger" @click.prevent="deletePost(post.id)">Delete</button></td>
                </tr>
            </tbody>
        </table>
  </div>
</template>

<script>
  export default {
      data() {
        return {
          posts: []
        }
      },
      created() {
      let uri = 'http://vuelaravelcrud.test/api/posts';
      this.axios.get(uri).then(response => {
        this.posts = response.data.data;
      });
    },
    methods: {
      deletePost(id)
      {
        let uri = `http://vuelaravelcrud.test/api/post/delete/${id}`;
        this.axios.delete(uri).then(response => {
          this.posts.splice(this.posts.indexOf(id), 1);
        });
      }
    }
  }
</script>

So, here, we have taken the click event in vue to grab the id of the current post and send that id to remove the data from the database as well as remove the data from the array at the client side using the splice function as well.

Finally, Vue Laravel CRUD Example Tutorial From Scratch is over. Thanks for taking. You can use the following Github Code for reference.

Github Code

The post Vue Laravel CRUD Example Tutorial From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2018/11/17/vue-laravel-crud-example-tutorial-from-scratch/feed/ 10
Vue Event Handling Example https://appdividend.com/2018/09/20/vue-event-handling-example/ https://appdividend.com/2018/09/20/vue-event-handling-example/#respond Thu, 20 Sep 2018 03:51:03 +0000 http://localhost/wordpress/?p=1724 Vue Event Handling Tutorial With Example

Vue Event Handling Example is today’s leading topic. Events are typically used in combination with functions, and the function will not be executed before the event occurs. In this tutorial, we will see how to listen for DOM events that we can use to trigger methods. Vue allows us to handle events triggered by the user. Handling events helps add interactivity to […]

The post Vue Event Handling Example appeared first on AppDividend.

]]>
Vue Event Handling Tutorial With Example

Vue Event Handling Example is today’s leading topic. Events are typically used in combination with functions, and the function will not be executed before the event occurs. In this tutorial, we will see how to listen for DOM events that we can use to trigger methods. Vue allows us to handle events triggered by the user. Handling events helps add interactivity to a web application by responding to the user’s input.

If you want to learn more about Vue.js then check out this Vue JS 2 – The Complete Guide (incl. Vue Router & Vuex) course.

Vue Event Handling Example

Let us install Vue.js using Vue CLI the following command.

vue create event

 

Vue Event Handling Example

I am using Vue CLI@3. So, if you have not installed then uninstall the previous version of CLI and then install the latest version of Vue CLI.

Hit the following command to open the project in VSCode.

cd event && code .

#Listening to Events

The user can interact with a view via click or mouse over or keyup to trigger an event on DOM elements. Vue.js API provides us with a v-on directive to handle these events.

Let us take an example of a v-on directive. We will add a click event on a button, and when we click that event, one event will be fired, and the counter value will increase by one.

Write the following code inside App.vue file.

<template>
  <div id="app">
    <label>The Count is: {{count}}</label><br />
    <button v-on:click="count++">Add Count</button>
  </div>
</template>

<script>

export default {
  name: 'app',
  data() {
    return {
      count: 0
    }
  }
}
</script>

Save the file and start the dev server.

npm run serve

Go to the http://localhost:8080/ 

#Method Event Handlers

In the above example, we have written the logic inside an expression like this: v-on:click=”count++.” Fortunately, we can also write one method that will do the increment like the following.

<template>
  <div id="app">
    <label>The Count is: {{count}}</label><br />
    <button v-on:click="addCounter()">Add Count</button>
  </div>
</template>

<script>

export default {
  name: 'app',
  data() {
    return {
      count: 0
    }
  },
  methods: {
    addCounter() {
      return this.count++;
    }
  }
}
</script>

Here, we are incrementing the counter inside the method, and it is the most convenient way because the sometimes logic code is large, so it’s a best practice to write the code inside the method. There is also shorthand of v-on syntax.

<button @click="addCounter()">Add Count</button>

#Methods in Inline Handlers

Instead of binding directly to the method name, we can also use methods in an inline JavaScript statement:

<template>
  <div id="app">
    <button v-on:click="greet('hi')">Greet hi</button>
    <button v-on:click="greet('what')">Ask what</button>
  </div>
</template>

<script>

export default {
  name: 'app',

  methods: {
    greet(value) {
      alert(value)
    }
  }
}
</script>

#Event Modifiers

It is a pervasive need to call event.preventDefault() or event.stopPropagation() inside event handlers. We can also do this easily inside methods; it would be better if the functions can be purely about the data logic rather than having to deal with the DOM events.

To approach this problem, Vue.js provides event modifiers for v-on. Remember that modifiers are directive postfixes denoted by a dot.

  • .stop
  • .prevent
  • .capture
  • .self
  • .once
  • .passive

There are frequently used method calls that are made when handling events. Vue has made it easier for us to implement these by using event modifiers.

For example, event.preventDefault() is the most often called when handling events to prevent the browsers default behavior like submitting the form.

Instead of having to write these out in the methods, we can use the modifiers provided by the vue-on directive.

<button @click.prevent="greet('what')">Ask what</button>

The other examples are the following.

<!-- the click event's propagation will be stopped -->
<a v-on:click.stop="doThis"></a>

<!-- the submit event will no longer reload the page -->
<form v-on:submit.prevent="onSubmit"></form>

<!-- modifiers can be chained -->
<a v-on:click.stop.prevent="doThat"></a>

<!-- just the modifier -->
<form v-on:submit.prevent></form>

<!-- use capture mode when adding the event listener -->
<!-- i.e. an event targeting an inner element is handled here before being handled by that element -->
<div v-on:click.capture="doThis">...</div>

<!-- only trigger handler if event.target is the element itself -->
<!-- i.e. not from a child element -->
<div v-on:click.self="doThat">...</div>

#Key Modifiers

We can also listen for keyboard events; we often need to check for common key codes. Vue also allows adding key modifiers for v-on when listening for key events:

<input v-on:keyup.13="submit">

Remembering all the keyCodes is a hassle, so Vue provides aliases for the most commonly used keys:

<!-- same as above -->
<input v-on:keyup.enter="submit">

<!-- also works for shorthand -->
<input @keyup.enter="submit">

Here is the full list of the key modifier aliases:

  • .enter
  • .tab
  • .delete (captures both “Delete” and “Backspace” keys)
  • .esc
  • .space
  • .up
  • .down
  • .left
  • .right

Finally, Vue Event Handling Example is over. Thanks for taking.

The post Vue Event Handling Example appeared first on AppDividend.

]]>
https://appdividend.com/2018/09/20/vue-event-handling-example/feed/ 0
Vue History Mode Routing Tutorial https://appdividend.com/2018/07/13/vue-history-mode-routing-tutorial/ https://appdividend.com/2018/07/13/vue-history-mode-routing-tutorial/#respond Fri, 13 Jul 2018 07:07:30 +0000 http://localhost/wordpress/?p=1316 Vue Router Example

Vue History Mode Routing Tutorial. The default mode for the vue-router is hash(#) mode as it uses the URL hash to simulate a full URL so that the page won’t be reloaded when the URL changes. To get rid of the hash mode, we can use the router’s history mode, which leverages the history.pushState API to achieve URL navigation without a page reload. […]

The post Vue History Mode Routing Tutorial appeared first on AppDividend.

]]>
Vue Router Example

Vue History Mode Routing Tutorial. The default mode for the vue-router is hash(#) mode as it uses the URL hash to simulate a full URL so that the page won’t be reloaded when the URL changes.

To get rid of the hash mode, we can use the router’s history mode, which leverages the history.pushState API to achieve URL navigation without a page reload.

If you want to learn more about Vue.js then check out this Vue JS 2 – The Complete Guide (incl. Vue Router & Vuex) course.
const router = new VueRouter({
  mode: 'history',
  routes: [...]
})

When using history mode, the URL will look “normal,” e.g., https://appdividend.com/category/vuejs. Beautiful!

Vue History Mode Routing Tutorial

Now, we install the Vue.js.

#1: Install Vue.js

Hit the following command to install Vue CLI. Skip this step if you have installed Vue CLI.

npm install -g @vue/cli
# OR
yarn global add @vue/cli

Now create a new Vue.js project using the following command.

vue create history

 

Vue History Mode Routing Tutorial

#2: Install Vue Router.

Install vue-router using the following command.

yarn add vue-router

# or

npm install vue-router --save

Now, configure the router inside src >> main.js file.

// main.js

import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'

Vue.config.productionTip = false
const routes = [];

const router = new VueRouter({ mode: 'history', routes: routes });

new Vue({
  render: h => h(App),
  router
}).$mount('#app')

Here, we have passed two parameters while instantiating the VueRouter object.

  1. mode
  2. routes array

If we do not define any mode then by default, it is a hash mode. But we have explicitly specified the mode, and that is history mode.

Okay, now we need to define the routes array. For that, we need to create some components.

#3: Install Bootstrap.

Type the following command to install Bootstrap 4.

yarn add bootstrap

# or

npm install bootstrap --save

Add the bootstrap file inside App.vue file.

App.vue

...
import 'bootstrap/dist/css/bootstrap.min.css';
...

#4: Create components.

Inside the components folder, create three components.

  1. HomeComponent.vue
  2. DashboardComponent.vue
  3. PostComponent.vue
// HomeComponent.vue

<template>
    <p>This is Home Component</p>
</template>
<script>
export default {
    
}
</script>

// DashboardComponent.vue

<template>
    <p>This is Dashboard Component</p>
</template>
<script>
export default {
    
}
</script>
// PostComponent.vue

<template>
    <p>This is Post Component</p>
</template>
<script>
export default {
    
}
</script>

#5: Import all the components inside main.js file.

We need to import all the component inside main.js file because we need to these components to create an array and assign the different routes.

// main.js

import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

import HomeComponent from './components/HomeComponent.vue'
import DashboardComponent from './components/DashboardComponent.vue'
import PostComponent from './components/PostComponent.vue'

import 'bootstrap/dist/css/bootstrap.min.css';

Vue.config.productionTip = false

const routes = [
  { path: 'home', name: 'Home', component: HomeComponent },
  { path: 'post', name: 'Post', component: PostComponent },
  { path: 'dashboard', name: 'Dashboard', component: DashboardComponent },
];

const router = new VueRouter({ mode: 'history', routes: routes });

new Vue({
  render: h => h(App),
  router
}).$mount('#app')

So, here we have assigned each component to path and name. Now we have registered the components with routes successfully.

Add the following code inside App.vue file.

// App.vue

<template>
  <div id="app">
    <nav class="navbar navbar-expand-sm bg-light">
      <ul class="navbar-nav">
        <li class="nav-item">
          <router-link :to="{ name: 'Home' }" class="nav-link">Home</router-link>
        </li>
        <li class="nav-item">
          <router-link :to="{ name: 'Dashboard' }" class="nav-link">Dashboard</router-link>
        </li>
        <li class="nav-item">
          <router-link :to="{ name: 'Post' }" class="nav-link">Post</router-link>
        </li>
      </ul>
    </nav>
    <router-view></router-view>
  </div>
</template>

<script>

export default {
  name: 'app'
}
</script>

Now start the development server using the following command.

npm run serve

You can see that history mode of routing is working great. Now, when we directly access the specific route, it will not work. For that first, you need to check your server if it is either apache or nginx.

#Apache

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

#nginx

location / {
  try_files $uri $uri/ /index.html;
}

 

The post Vue History Mode Routing Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2018/07/13/vue-history-mode-routing-tutorial/feed/ 0
Vue Elasticsearch Tutorial With Node.js From Scratch https://appdividend.com/2018/07/05/vue-elasticsearch-tutorial-with-node-js/ https://appdividend.com/2018/07/05/vue-elasticsearch-tutorial-with-node-js/#respond Thu, 05 Jul 2018 09:37:22 +0000 http://localhost/wordpress/?p=1278 Vue.js Elastic Tutorial

Vue Elasticsearch Tutorial With Node.js From Scratch is today’s leading topic.  We build a frontend in Vue.js and then send a network request to the node.js server and node will query the data to the elastic server. It will get a response and send the JSON response back to the Vue.js client. Now, first, we create […]

The post Vue Elasticsearch Tutorial With Node.js From Scratch appeared first on AppDividend.

]]>
Vue.js Elastic Tutorial

Vue Elasticsearch Tutorial With Node.js From Scratch is today’s leading topic.  We build a frontend in Vue.js and then send a network request to the node.js server and node will query the data to the elastic server. It will get a response and send the JSON response back to the Vue.js client. Now, first, we create a Vue.js frontend and then create a node.js server and index all the data to the elastic-server. Then send a request to the node server and fetch the data. So it is pretty simple stuff to understand. You can find full documentation of elasticsearch here.

If you want to learn more about Vue.js then check out this Vue JS 2 – The Complete Guide (incl. Vue Router & Vuex) course.

# Vue Elasticsearch Tutorial With Node.js

Now let us dive into the programming. First, install Vue.js.

#Step 1: Install Vue.js

We install Vue.js using VueCLI. So if you have not installed Vue CLI, then you can install it using the following command.

npm install -g @vue/cli
# OR
yarn global add @vue/cli

Now create a new Vue.js project using the following command.

vue create vue-elastic

 

Vue Elasticsearch Tutorial With Node.js From Scratch

Go into the project folder.

cd vue-elastic

Start the dev server using the following command.

npm run serve

#Step 2: Create Bootstrap Form For Search.

Now, install the Bootstrap 4 using the following command.

npm install bootstrap --save

# or

yarn add bootstrap

Import the bootstrap 4 file inside src >> main.js file.

// main.js

import Vue from 'vue'
import App from './App.vue'

import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

Vue.config.productionTip = false

new Vue({
  render: h => h(App)
}).$mount('#app')

Okay, replace the existing code by the following code inside App.vue file.

<!-- App.vue -->

<template>
  <div id="app" class="container">
    <div class="input-group input-group-lg bottom">
      <div class="input-group-prepend">
        <span class="input-group-text">Search</span>
      </div>
      <input type="text" class="form-control col-md-6">
    </div>
  </div>
</template>

<script>

export default {
  
}
</script>

<style>
  .bottom {
    margin-top: 50px;
    margin-left: 200px;
  }
</style>

 

Vue Elasticsearch example

Next step is to add the @keydown event to the search area. We need to do this because when the user starts typing in the search box, then we send a network request to the server with the search query and then get a result and display the result. So write the following code inside App.vue file.

// App.vue

<template>
  <div id="app" class="container">
    <div class="input-group input-group-lg bottom">
      <div class="input-group-prepend">
        <span class="input-group-text">Search</span>
      </div>
      <input type="text" 
        class="form-control col-md-6" 
        @keyup.prevent="search"
        v-model="query" />
    </div>
  </div>
</template>

<script>

export default {
  data() {
    return {
      query: ''
    }
  },
  methods: {
    search() {
      console.log(this.query);
      return this.query;
    }
  }
}
</script>

<style>
  .bottom {
    margin-top: 50px;
    margin-left: 200px;
  }
</style>

#Step 3: Install Axios HTTP Promise based library.

Type the following command to install Axios Promise based HTTP library.

npm install axios vue-axios --save

# or

yarn add axios vue-axios

We have not created the node.js server, but we will create in a minute. Bur first, we setup axios to send a network request to the server.

Okay, now add the axios and vue-axios inside the  main.js file.

// main.js

import Vue from 'vue'
import App from './App.vue'
import axios from 'axios';
import VueAxios from 'vue-axios';

import '../node_modules/bootstrap/dist/css/bootstrap.min.css'

Vue.config.productionTip = false

Vue.use(axios, VueAxios);

new Vue({
  render: h => h(App)
}).$mount('#app')

Finally, we can use Axios inside App.vue file.

// App.vue

export default {
  data() {
    return {
      query: '',
      data: []
    }
  },
  methods: {
    search() {
        axios.get("http://localhost:5000/search?q=" + this.query)
              .then(response => {
                console.log(response.data);
                this.data = response.data;
          })
    }
  }
}

So, we will send a network request to the node.js server which is running at port 5000. Right now, it is not running because we have not created yet. So let us create in the next step.

#Step 4: Create node.js web server.

Inside your vue-elastic project, create one folder called server and inside that create one file called server.js.

First, install the following node.js dependencies using the following command.

npm install express body-parser elasticsearch cors --save

Write the following code inside a server.js file.

// server.js

const express = require('express');
const app = express();

const PORT = 5000;

app.listen(PORT, function() {
    console.log('Your node.js server is running on PORT: ',PORT);
});

You can start this node.js server by typing the following command inside server folder.

node server

#Step 5: Install Elasticsearch on the local machine.

If you have already installed Elasticsearch on the mac, then you do not need this step. Otherwise, you can continue with this step. So type the following command to install Elasticsearch via homebrew.

brew install elasticsearch

It will install it and now start the services using the following command.

brew services start elasticsearch

Now, we need to connect our node.js application to the elastic server.

// server.js

const express = require('express');
const app = express();
const elasticsearch = require('elasticsearch');
const fs = require('fs');

const PORT = 5000;

const client = new elasticsearch.Client({
    host: '127.0.0.1:9200',
    log: 'error'
 });

 client.ping({ requestTimeout: 30000 }, function(error) {
    if (error) {
        console.error('elasticsearch cluster is down!');
    } else {
        console.log('Everything is ok');
    }
});

app.listen(PORT, function() {
    console.log('Your node.js server is running on PORT:',PORT);
});

Now, restart the node.js server and see console. You can get like this in the console.

 

Vue Express Elasticsearch example

#Step 6: Create an index and indexing of data.

We need the data to index. So inside server folder, create one file called data.json and add the following code inside it. We will search some of the Game of Thrones main characters.

[
    {
        "cast_name": "Tyrion Lannister",
        "og_name": "Peter Dinklage",
        "url": "https://vignette.wikia.nocookie.net/gameofthrones/images/5/58/Tyrion_main_s7_e6.jpg/revision/latest?cb=20170818050344"
    },
    {
        "cast_name": "Daenerys Targaryen",
        "og_name": "Emilia Clarke",
        "url": "https://vignette.wikia.nocookie.net/gameofthrones/images/5/5f/Daenerys_Dragonpit.jpg/revision/latest?cb=20171015095128"
    },
    {
        "cast_name": "Jon Snow",
        "og_name": "kit Harington",
        "url": "https://vignette.wikia.nocookie.net/gameofthrones/images/a/a5/Profile-JonSnow-707.png/revision/latest?cb=20170828030553"
    },
    {
        "cast_name": "Cersei Lannister",
        "og_name": "Lena Heady",
        "url": "https://vignette.wikia.nocookie.net/gameofthrones/images/c/c3/Profile-CerseiLannister.png/revision/latest?cb=20170828071355"
    },
    {
        "cast_name": "Sansa Stark",
        "og_name": "Sophie Turner",
        "url": "https://vignette.wikia.nocookie.net/gameofthrones/images/7/7e/Sansastark706.jpg/revision/latest/scale-to-width-down/316?cb=20170828072803"
    },
    {
        "cast_name": "Arya Stark",
        "og_name": "Maisie Williams",
        "url": "https://upload.wikimedia.org/wikipedia/en/3/39/Arya_Stark-Maisie_Williams.jpg"
    },
    {
        "cast_name": "Jaime Lannister",
        "og_name": "Nikolaj Coster-Waldau",
        "url": "https://vignette.wikia.nocookie.net/gameofthrones/images/e/eb/Jaime.jpg/revision/latest?cb=20170818052054"
    },
    {
        "cast_name": "Ramsay Bolton",
        "og_name": "Iwan Rheon",
        "url": "https://vignette.wikia.nocookie.net/gameofthrones/images/d/d2/Ramsay_S06E09_RESZIED_FOR_INFOBOX.jpg/revision/latest?cb=20160622071734"
    },
    {
        "cast_name": "Petyr Baelish",
        "og_name": "Aidan Gillen",
        "url": "https://vignette.wikia.nocookie.net/gameofthrones/images/9/9f/Profile-Littlefinger.png/revision/latest?cb=20170826005231"
    },
    {
        "cast_name": "Joffrey Baratheon",
        "og_name": "Jack Gleeson",
        "url": "https://vignette.wikia.nocookie.net/gameofthrones/images/2/25/Joffrey_Season_4_Episode_2_TLATR.jpg/revision/latest?cb=20171105180252"
    }
]

Now, we need to index these data. So let us create another file inside server folder called elasticsearch.js and add the following code in it.

// elasticsearch.js

const elasticsearch = require('elasticsearch');
const fs = require('fs');

const client = new elasticsearch.Client({
    hosts: [ 'http://localhost:9200']
});

client.indices.create({
    index: 'vue-elastic'
}, function(error, response, status) {
    if (error) {
        console.log(error);
    } else {
        console.log("created a new index", response);
    }
});

const bulkIndex = function bulkIndex(index, type, data) {
    let bulkBody = [];
  
    data.forEach(item => {
      bulkBody.push({
        index: {
          _index: index,
          _type: type
        }
      });
      bulkBody.push(item);
    });
  
client.bulk({body: bulkBody})
    .then(response => {
      let errorCount = 0;
      response.items.forEach(item => {
        if (item.index && item.index.error) {
          console.log(++errorCount, item.index.error);
        }
      });
      console.log(
        `Successfully indexed ${data.length - errorCount}
         out of ${data.length} items`
      );
    })
    .catch(console.err);
  };

async function indexData() {
    const articlesRaw = await fs.readFileSync('./data.json');
    const articles = JSON.parse(articlesRaw);
    console.log(`${articles.length} items parsed from data file`);
    bulkIndex('vue-elastic', 'characters_list', articles);
  }

indexData();

Save the file and open the terminal inside the server folder and hit the following command.

node elasticsearch.js

It will index the data. So now our game of thrones characters are ready to query.

#Step 7: Create the query.

Inside the server.js file, add the following code.

// server.js

const express = require('express');
const app = express();
const elasticsearch = require('elasticsearch');
const cors = require('cors');
const bodyParser = require('body-parser');

app.set('port', process.env.PORT || 5000 );
app.use(cors());
app.use(bodyParser.json());

const client = new elasticsearch.Client({
    host: '127.0.0.1:9200',
    log: 'error'
 });

client.ping({ requestTimeout: 30000 }, function(error) {
    if (error) {
        console.error('elasticsearch cluster is down!');
    } else {
        console.log('Everything is ok');
    }
});

app.get('/search', function (req, res){
    
    let body = {
      size: 100,
      from: 0,
      query: {
        match: {
                cast_name: {
                    query: req.query['q'],
                    fuzziness: 4
                }
            }
        }
    }
   
    client.search({index:'vue-elastic', body:body, type:'characters_list'})
    .then(results => {
            res.send(results.hits.hits);
        
    })
    .catch(err=>{
      console.log(err)
      res.send([]);
    });
  
  })

app.listen(app.get('port'), function() {
    console.log('Your node.js server is running on PORT: ',app.get('port'));
});

So, finally when the user tries to search any phrase, it will get this get /search route, and we pass the query parameter.

According to the query, it will find the results and send back to the client.

#Step 8: Display the queried data.

Inside App.vue file, add the following code.

<!-- App.vue -->

<template>
  <div id="app" class="container">
    <div class="input-group input-group-lg bottom">
      <div class="input-group-prepend">
        <span class="input-group-text">Search</span>
      </div>
      <input type="text" 
        class="form-control col-md-6" 
        @keyup.prevent="search"
        v-model="query" />
    </div>
    
    <div  class="card-row">
    <div v-if="data" v-for="(value, index) in data" 
      :key="index"
      :ref="`card_${index}`"
         class="card">
      
      <img class="card-image" :src="value._source.url">
      
      <div class="card-footer">
        <h3 class="card-title">{{value._source.cast_name}}</h3>
        <p class="card-text">by 
          <span class="card-author">{{value._source.og_name}}</span>
        </p>
      </div>
    </div>
  </div>
  </div>
</template>


<script>

export default {
  data() {
    return {
      query: '',
      data: []
    }
  },
  methods: {
    search() {
        this.axios.get('http://localhost:5000/search?q='+this.query)
              .then(response => {
                this.data = response.data;
          })
    }
  }
}
</script>

<style>
body {
  background-color: #E1E7E7;
}

  .bottom {
    margin-top: 50px;
    margin-left: 200px;
  }
.card-row {
  display: flex;
  justify-content: center;
  align-items: center;  
  min-width: 780px;
  width: 100%;
  height: 500px;
}
.card {
  position: relative;
  background-color: #FFFFFF;
  height: 370px;
  width: 240px;
  margin: 10px;
  overflow: hidden;
  box-shadow: 0px 2px 4px 0px rgba(0,0,0,0.5);
}
.card-image {
  position: absolute;
  left: -9999px;
  right: -9999px;
  margin: auto;
  height: 220px;
  min-width: 100%;
}
.card-footer {
  position: absolute;
  bottom: 0;
  height: 130px;
  padding: 10px 15px;
  font-family: Helvetica;
}
.card-text {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.7);
}
.card-title {
  font-family: Serif;
}
.card-author {
  font-size: 14px;
  color: #BAB096;
}
</style>

Finally, we can search the data from Vue.js using elasticsearch.

Vue Elasticsearch Tutorial is over. Thanks for taking.

Github Code

The post Vue Elasticsearch Tutorial With Node.js From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2018/07/05/vue-elasticsearch-tutorial-with-node-js/feed/ 0
How To Create Hover Animation In Vuejs https://appdividend.com/2018/07/04/how-to-create-hover-animation-in-vuejs/ https://appdividend.com/2018/07/04/how-to-create-hover-animation-in-vuejs/#comments Wed, 04 Jul 2018 10:34:19 +0000 http://localhost/wordpress/?p=1268 Animation Effect in Vue.js

In this example, I have taught How To Create Hover Animation In Vuejs. In this tutorial, we do not use any CSS frameworks. We use CSS3 properties to accomplish the goal. Apply animation effect on hover in Vue.js is very easy.  We create a simple card with text and image. Then when we hover that card, the […]

The post How To Create Hover Animation In Vuejs appeared first on AppDividend.

]]>
Animation Effect in Vue.js

In this example, I have taught How To Create Hover Animation In Vuejs. In this tutorial, we do not use any CSS frameworks. We use CSS3 properties to accomplish the goal. Apply animation effect on hover in Vue.js is very easy.  We create a simple card with text and image. Then when we hover that card, the image size will be increased but do not spread out of the card. So we use CSS transition property. Also, we use mouseover event from Vue.js to apply animation effect when the user hovers the particular card. Now let us start this Create Hover Animation in Vuejs example.

If you want to learn more about Vue.js then check out this Vue JS 2 – The Complete Guide (incl. Vue Router & Vuex) course.

Create Hover Animation In Vuejs

Let us install Vue.js using the Vue CLI. If you have not installed the Vue CLI previously then install it using the following command.

#Step 1: Install Vue.js.

npm install -g @vue/cli
# OR
yarn global add @vue/cli

Now create a new Vue.js project using the following command.

vue create animation

Okay, now inside src >> App.vue file add the following code to create a Card. Remember, we are not using Bootstrap framework so that we will write the css from scratch.

<!-- App.vue -->

<div id="app">
  <div class="card-row">
    <div class="card">
      
      <img class="card-image" src="https://www.gstatic.com/webp/gallery3/2_webp_ll.png">
      
      <div class="card-footer">
        <h3 class="card-title">Title</h3>
        <p class="card-text">by 
          <span class="card-author">Author</span>
        </p>
      </div>
    </div>
  </div>
</div>

So, we have created the Card, but we need to build its styles. So inside src >> assets folder, create one file called style.css and add the css code inside it.

body {
  background-color: #E1E7E7;
}

.card-row {
  display: flex;
  justify-content: center;
  align-items: center;  
  min-width: 780px;
  width: 100%;
  height: 500px;
}

We use flexbox for styling because it is effortless to use. Next step is to style the card.

#Step 2: Style the Card.

Write the following code inside the style.css file.

.card {
  position: relative;
  background-color: #FFFFFF;
  height: 370px;
  width: 240px;
  margin: 10px;
  overflow: hidden;
  box-shadow: 0px 2px 4px 0px rgba(0,0,0,0.5);
}

The position of the card will be relative. Overflow must be hidden because we do not need to display the image outside of the card when it is resized. So overflow will always be hidden. The box-shadow property adds the shadow to the card.

#Step 3: Style the Image.

Add the following code inside the style.css file.

.card-image {
  position: absolute;
  left: -9999px;
  right: -9999px;
  margin: auto;
  height: 220px;
  min-width: 100%;
}

The main reason I have taken a left and right to -9999px is that when we hover the image, animation effect will be applied so, it should center the image horizontally. The position is absolute, and min-width is 100%.

#Step 4: Style the Footer.

Write the following code inside a style.css file.

.card-footer {
  position: absolute;
  bottom: 0;
  height: 130px;
  padding: 10px 15px;
  font-family: Helvetica;
}
.card-text {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.7);
}
.card-title {
  font-family: Serif;
}
.card-author {
  font-size: 14px;
  color: #BAB096;
}

It is pretty same stuff, we have assigned different classes to its styles. Nothing more complicated.

#Step 5: Add the data.

We have created one card, but now, we will create five cards. So we need an array of data. So let us define the data inside App.vue file. Also, we have to import the style.css inside App.vue file to see the changes.

// App.vue

import './assets/style.css';

export default {
  name: 'app',
  data() {
    return {
      cards: [
        {
         title: 'Gallery', 
         author: 'Walder Frey', 
         image: 'http://www.gstatic.com/webp/gallery/1.webp'
        },
        {
          title: 'Penguin', 
          author: 'Ramsey Bolton', 
          image: 'https://www.gstatic.com/webp/gallery3/2_webp_ll.png'
        },
        {
          title: 'Flower', 
          author: 'Joffrey Baratheon', 
          image: 'https://www.gstatic.com/webp/gallery3/1.png'
        },
         {
          title: 'Flower Pot', 
          author: 'Cersie Lannister', 
          image: 'https://www.fiftyflowers.com/site_files/FiftyFlowers/Image/Product/Make_Your_Own_Centerpiece_Close_Up_350_a425aad8.jpg'
        },
         {
          title: 'Rose', 
          author: 'Roose Bolton', 
          image: 'https://res.cloudinary.com/prestige-gifting/image/fetch/fl_progressive,q_95,e_sharpen:50,w_480/e_saturation:05/https://www.prestigeflowers.co.uk/images/NF4016-130116.jpg'
        }
      ]
    }
  }
}

And now in our template, we can render those cards with a v-for directive.

<!-- App.vue -->
<div id="app">
  <div class="card-row">
    <div v-for="(card, index) in cards" 
      :key="index"
      :ref="`card_${index}`"
         class="card">
      
      <img class="card-image" :src="card.image">
      
      <div class="card-footer">
        <h3 class="card-title">{{card.title}}</h3>
        <p class="card-text">by 
          <span class="card-author">{{card.author}}</span>
        </p>
      </div>
    </div>
  </div>
</div>

 

How To Create Hover Animation In Vuejs

#Step 6: Add the hover effect.

I am writing the whole code here. So bear with me.

First, I am showing the full code of the style.css file.

body {
    background-color: #E1E7E7;
  }
  
  .card-row {
    display: flex;
    justify-content: center;
    align-items: center;  
    min-width: 780px;
    width: 100%;
    height: 500px;
  }
  
  .card {
    position: relative;
    background-color: #FFFFFF;
    height: 370px;
    width: 240px;
    margin: 10px;
    overflow: hidden;
    box-shadow: 0px 2px 4px 0px rgba(0,0,0,0.5);
  }
  
  .card-image {
    /* center horizontally overflown image */
    position: absolute;
    left: -9999px;
    right: -9999px;
    margin: auto;
  
    height: 220px;
    min-width: 100%;
  
    transition: height 0.3s, opacity 0.3s;
  }
  .card-image.selected {
    height: 410px;
    opacity: 0.3;
  }
  
  .card-footer {
    position: absolute;
    bottom: 0;
    height: 130px;
    padding: 10px 15px;
    font-family: Helvetica;
  }
  .card-text {
    font-size: 14px;
    color: rgba(0, 0, 0, 0.7);
  }
  .card-title {
    font-family: Serif;
  }
  .card-author {
    font-size: 14px;
    color: #BAB096;
    transition: color 0.3s;
  }
  .card-author.selected {
    color: #6a6456;
  }
  .card {
    /* the other rules */
    transition: height 0.3s, box-shadow 0.3s;
  }
  .card:hover {
    height: 410px;
    box-shadow: 20px 20px 40px 0px rgba(0,0,0,0.5);
  }

Also, write the following code inside App.vue file.

<!-- App.vue -->

<template>
  <div id="app">
    <div class="card-row">
    <div v-for="(card, index) in cards" 
        :key="index"
        :ref="`card_${index}`"
        @mouseover="hoverCard(index)"
        @mouseout="hoverCard(-1)"
        class="card">
      
      <img class="card-image" 
        :class="{'selected': isSelected(index)}"
        :src="card.image">
      
      <div class="card-footer">
        <h3 class="card-title">{{card.title}}</h3>
        <p class="card-text">by 
          <span 
            class="card-author" 
            :class="{'selected': isSelected(index)}">
                {{card.author}}
          </span>
        </p>
      </div>
    </div>
  </div>
  </div>
</template>

<script>

import './assets/style.css';

export default {
  name: 'app',
  data() {
    return {
      selectedCard: -1,
      cards: [
        {
         title: 'Gallery', 
         author: 'Walder Frey', 
         image: 'http://www.gstatic.com/webp/gallery/1.webp'
        },
        {
          title: 'Penguin', 
          author: 'Ramsey Bolton', 
          image: 'https://www.gstatic.com/webp/gallery3/2_webp_ll.png'
        },
        {
          title: 'Flower', 
          author: 'Joffrey Baratheon', 
          image: 'https://www.gstatic.com/webp/gallery3/1.png'
        },
         {
          title: 'Flower Pot', 
          author: 'Cersie Lannister', 
          image: 'https://www.fiftyflowers.com/site_files/FiftyFlowers/Image/Product/Make_Your_Own_Centerpiece_Close_Up_350_a425aad8.jpg'
        },
         {
          title: 'Rose', 
          author: 'Roose Bolton', 
          image: 'https://res.cloudinary.com/prestige-gifting/image/fetch/fl_progressive,q_95,e_sharpen:50,w_480/e_saturation:05/https://www.prestigeflowers.co.uk/images/NF4016-130116.jpg'
        }
      ]
    }
  },
  methods: {
    hoverCard(selectedIndex) {
      this.selectedCard = selectedIndex
    },
    isSelected(cardIndex) {
      return this.selectedCard === cardIndex
    }
  }
}
</script>

So, here, I have defined the two events.

  1. @mouseover
  2. @mouseout

So when we hover any image, we pass an index to the function defined in mouseover event.

Now, that function assigns that index to the selected property.

The reason behind that is very simple when the user hovers the image at that time, that image is selected and we need to apply the hover css classes to that image. 

<img class="card-image" 
        :class="{'selected': isSelected(index)}"
        :src="card.image">

So, if the selected image has that index then we bind the selected class and the animation effect will be applied. The following style.css code help us to apply the animated effect. It is a simple CSS 3 rules.

.card-image {
  /* the other rules */
  transition: height 0.3s, opacity 0.3s;
}
.card-image.selected {
  height: 410px;
  opacity: 0.3;
}

Now, If you have written both style.css and App.vue file then go to the browser and see the result.

Finally, our  How To Create Hover Animation In Vuejs tutorial with an example is over. Thanks!!

The post How To Create Hover Animation In Vuejs appeared first on AppDividend.

]]>
https://appdividend.com/2018/07/04/how-to-create-hover-animation-in-vuejs/feed/ 2
Nuxt js Laravel Authentication Tutorial With Example https://appdividend.com/2018/06/22/nuxt-js-laravel-authentication-tutorial/ https://appdividend.com/2018/06/22/nuxt-js-laravel-authentication-tutorial/#comments Fri, 22 Jun 2018 22:32:13 +0000 http://localhost/wordpress/?p=1152 Nuxt Laravel Authentication Example

Nuxt js Laravel Authentication Tutorial With Example is the today’s leading topic. We use Nuxt.js as a frontend and Laravel as a backend. We create an API to that authenticate the user sent from the client. In return, we send a JSON Web Token. After signing in, we will send a JWT token with the request […]

The post Nuxt js Laravel Authentication Tutorial With Example appeared first on AppDividend.

]]>
Nuxt Laravel Authentication Example

Nuxt js Laravel Authentication Tutorial With Example is the today’s leading topic. We use Nuxt.js as a frontend and Laravel as a backend. We create an API to that authenticate the user sent from the client. In return, we send a JSON Web Token. After signing in, we will send a JWT token with the request to verify in the server that user is valid and it needs to assign the proper resources he has requested. We use Tymon laravel package to generate the token in the server side.

If you want to learn more about Vue.js then check out this Vue JS 2 – The Complete Guide (incl. Vue Router & Vuex) course.

Nuxt js Laravel Authentication Tutorial

We start our project by installing two projects.

  1. Laravel
  2. Nuxt.js

Step 1: Install Laravel and Nuxt.js.

Let us install Laravel 5.6 using the following command. I have used Laravel Valet.

laravel new laravel-server

For installing Nuxt.js, we need to install it community starter template. You can find it more in this URL: https://github.com/nuxt-community/starter-template

Go to your terminal and install nuxt.js starter template using the following command. But before that, we need to install @vue/cli-init globally using the following command. Then we install the nuxt template.

yarn global add @vue/cli-init

Now, install the starter template.

vue init nuxt-community/starter-template nuxt-client

 

Nuxt js Laravel Authentication Tutorial With Example

Go into the nuxt-client project and install the dependencies using the following command.

cd nuxt-client

npm install

Now, we can start the development server of Nuxt.js using the following command.

npm run dev

Switch to the browser and access this URL: http://localhost:3000/. You can see something like below.

Nuxt js Laravel Authentication

Step 2: Configure Laravel 5.6.

Go to the Laravel project and open in your favorite editor. Mine is VSCode.

cd laravel-server

code .

Configure the database inside the .env file.

Migrate the database table using the following command.

php artisan migrate

Now, we are using Laravel as an API, so we do not need web routes in our project. Simply client makes a particular request, and laravel server returns a JSON response. That is it. Nothing more complicated.

So, we do not need any of the controller files that reside in app >> Http >> Controller >> Auth folder. So remove it and create a new controller by the following command.

php artisan make:controller Auth\\AuthController

So it will create an AuthController.php file inside Controller’s Auth folder.

We write all the functions like Register, Login, and, Logout function inside this AuthController file.

Also, remove routes >> web.php file and welcome.blade.php view file because we have our client.

All our api routes will go on inside routes >> api.php file.

Step 3: Install tymondesigns/jwt-auth package.

Inside Laravel project root, type the following command. We need to install version 1 of the package.

composer require tymon/jwt-auth

After it finishes installing, go to the composer.json file and change the version of the package.

"require": {
        "php": "^7.1.3",
        "fideloper/proxy": "^4.0",
        "laravel/framework": "5.6.*",
        "laravel/tinker": "^1.0",
        "tymon/jwt-auth": "1.0.0-rc.2"
    },

Now, type the following command to update the package.

composer update

It will update the package.

Configure the Tymon package.

First, go to the User.php model, and that model needs to implement the JWTSubject interface.

The interface comes with the two methods that need to be implemented by User model.

Write the following code inside User.php file. We have just added two new functions and implemented an interface.

<?php

// User.php

namespace App;

use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    public function getJWTCustomClaims()
    {
        return [];
    }
}

Now, publish the package using the following command.

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"

It will copy the file to this path: /config/jwt.php

Now, generate the jwt secret using the following command.

php artisan jwt:secret

Now, go to the config >> auth.php file and set the guard to api because we use Laravel as an API.

// auth.php

'defaults' => [
   'guard' => 'api',
    'passwords' => 'users',
 ],

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
        ],
    ],

We have changed the default guard to api and api uses the jwt driver instead of the token. Save the file, and you are good to go.

Step 4: Create Registration Functionality.

Now, we have created the AuthController.php file. So, write the first route inside routes >> api.php file. Remove existing code in an api.php file.

<?php

// api.php

Route::post('register', 'Auth\AuthController@register')->name('register');

Now, write the code inside AuthController.php file to register a user.

<?php

// AuthController.php

namespace App\Http\Controllers\Auth;

use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|unique:users,email|email',
            'password' => 'required'
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password)
        ]);
  
        return $user;
    }
}

So, first, the request will be verified again the server side validation and then create a User in the database and return that user.

Now, we use API Resources to return a JSON data in the standard format. So let us create User Resource using the following command.

php artisan make:resource UserResource

It will create a folder inside app >> Http called Resources and inside that it will create a file called UserResource.php.

We need to modify the UserResource.php file and edit the function toArray(). We need to return an array that contains only properties that client needs to display at the front end side. So let us do that.

<?php

// UserResource.php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email
        ];
    }
}

Now, import UserResource.php file inside AuthController.php file.

<?php

// AuthController.php

namespace App\Http\Controllers\Auth;

use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Resources\UserResource;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|unique:users,email|email',
            'password' => 'required'
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password)
        ]);

        return new UserResource($user);
    }
}

Okay, now after registering a user, it will send a following formatted JSON response. We can test the request in the Postman.

Laravel API Authentication

 

Now, we can see that the user is created. Next step is that we need to sign in that user in our application and generate the JWT Token and send that token to the client. So we send the User object as well as the token to the Nuxt.js client.

// RegisterController.php

public function register(Request $request)
{
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|unique:users,email|email',
            'password' => 'required'
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password)
        ]);

        if(!$token = auth()->attempt($request->only(['email', 'password'])))
        {
            return abort(401);
        }

        return (new UserResource($user))
            ->additional([
               'meta' => [
                 'token' => $token
             ]
        ]);
}

Here, we have checked the authentication against the newly created user. If the user is valid, then it will generate a JWT token and send back to the client. We can test in the Postman by sending another request to the server.

Laravel JWT Authentication Example

 

Step 5: Create Login Functionality.

Okay, so Registration is done. Now, go to the routes >> api.php file and add one route for login.

<?php

// api.php

Route::post('register', 'Auth\AuthController@register')->name('register');
Route::post('login', 'Auth\AuthController@login')->name('login');

Create a login() function inside AuthController and add the following code to sign in the user and generate the token.

// AuthController.php

public function login(Request $request)
{
        $this->validate($request, [
            'email' => 'required',
            'password' => 'required'
        ]);

        if(!$token = auth()->attempt($request->only(['email', 'password'])))
        {
            return response()->json([
                'errors' => [
                    'email' => ['There is something wrong! We could not verify details']
            ]], 422);
        }

        return (new UserResource($request->user()))
                ->additional([
                    'meta' => [
                        'token' => $token
                    ]
                ]);
}

So, if the requested user is valid, then it will send a token to the client.

Also, we need to define one another endpoint for our api. This api endpoint is for retrieving the current signed in user.

// api.php

Route::get('/user', 'Auth\AuthController@user');

Write the user() function inside AuthController.php file.

// AuthController.php

public function user(Request $request)
{
     return new UserResource($request->user());
}

Step 6: Install CORS module.

When we submit the request from the client side, we get an error inside browser called cross-site request origin. We get this error because our Nuxt.js application is running on PORT: 3000 and Laravel server is running on different port. So we need to resolve this error by installing a laravel-cors module.

Install the CORS module in the Laravel project by the following command.

composer require barryvdh/laravel-cors

Inside app >> Http >> Kernel.php file, add the CORS middleware in the api guard.

// Kernel.php

'api' => [
    'throttle:60,1',
     'bindings',
     \Barryvdh\Cors\HandleCors::class,
],

Publish the cors package using the following command.

php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"

That is it. Now, we can send a network request from the nuxt-client to the laravel-server.

Step 7: Install Bootstrap 4 inside a Nuxt project.

Install Bootstrap 4 using the following command.

yarn add bootstrap

# or

npm install bootstrap --save

Inside the root folder of nuxt-client, there is one file called nuxt.config.js.

We need to add the following lines of code inside that file.

// nuxt.config.js

css: ['./node_modules/bootstrap/dist/css/bootstrap.css'],
plugins: ['~plugins/bootstrap.js']

Also, we need to include jquery. So write the following code to include jQuery.

// nuxt.config.js

const webpack = require('webpack');

build: {
    vendor: ['jquery', 'bootstrap'],
    plugins: [
      new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery'
      })
    ],
    extend (config, { isDev, isClient }) {
      if (isDev && isClient) {
        config.module.rules.push({
          enforce: 'pre',
          test: /\.(js|vue)$/,
          loader: 'eslint-loader',
          exclude: /(node_modules)/
        })
      }
    }
  },

So, our nuxt.config.js file looks like below.

// nuxt.config.js

const webpack = require('webpack')

module.exports = {
  head: {
    title: 'nuxt-client',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: 'Nuxt.js project' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },

  loading: { color: '#3B8070' },

  build: {
    vendor: ['jquery', 'bootstrap'],
    plugins: [
      new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery'
      })
    ],
    extend (config, { isDev, isClient }) {
      if (isDev && isClient) {
        config.module.rules.push({
          enforce: 'pre',
          test: /\.(js|vue)$/,
          loader: 'eslint-loader',
          exclude: /(node_modules)/
        })
      }
    }
  },
  css: ['./node_modules/bootstrap/dist/css/bootstrap.css'],
  plugins: ['~plugins/bootstrap.js']
}

Now, inside plugins folder, we need to create one file called bootstrap.js and write the following code inside it.

// bootstrap.js

if (process.BROWSER_BUILD) {
    require('bootstrap')
}

Save the file and go to the pages >> index.vue file and edit with the following code. Remove all other code.

// index.vue

<template>
  <div class="container">
    Page
  </div>
</template>

<script>

export default {
  
}
</script>

Go to the browser, and you can see that, Bootstrap 4 is successfully integrated.

Step 8: Create Layout inside a Nuxt project.

Now, inside layouts folder, create one more folder called partials and inside that, create one Vue component called Navbar.js. Write the following code inside Navbar.js file.

// Navbar.js

<template>
    <nav class="navbar navbar-expand-sm bg-light">
        <div class="container">
            <a class="navbar-brand" href="">
                Nuxt Laravel Auth
            </a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false">
                <span class="navbar-toggler-icon"></span>
            </button>

            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <!-- Right Side Of Navbar -->
                <ul class="navbar-nav ml-auto">
                    <!-- Authentication Links -->
                        <li class="nav-item">
                            <a class="nav-link" href="">Login</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="">Register</a>
                        </li>
                        <li class="nav-item dropdown">
                            <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                                Krunal <span class="caret"></span>
                            </a>

                            <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
                                <a class="dropdown-item" href="">
                                    Logout
                                </a>  
                            </div>
                        </li>
                </ul>
            </div>
        </div>
    </nav>
</template>
<script>
export default {
    
}
</script>

Import this component inside layouts >> default.vue file.

// default.vue

<template>
  <div>
    <Navbar />
    <nuxt/>
  </div>
</template>
<script>
import Navbar from './partials/Navbar';
export default {
  components: {
    Navbar
  }
}
</script>

Save the file and go to the browser. You can see, we have our navbar with the items like register, login, logout, username. Of course, the navbar items will be changed in the future based on logged in and out.

 

Step 9: Setup Nuxt Authentication.

We need to install the following two modules.

  1. @nuxjs/axios
  2. @nuxtjs/auth
yarn add @nuxtjs/axios @nuxtjs/auth

# or

npm install @nuxtjs/axios @nuxtjs/auth --save

Now, register these modules inside the nuxt.config.js file.

// nuxtjs.config.js

loading: { color: '#3B8070' },

modules: ['@nuxtjs/auth', '@nuxtjs/axios'],

Now, configure both of these modules individually inside a nuxt.config.js file.

// nuxt.config.js

axios: {
    baseURL: 'http://laravel-server.test/api'
  },
  auth: {
    strategies: {
      local: {
        endpoints: {
          login: { url: 'login', method: 'post', propertyName: 'meta.token' },
          user: { url: 'user', method: 'get', propertyName: 'data' },
          logout: {}
        }
      }
    }
  },

So, here, we have defined the baseURL for a laravel-server API and also define the Auth endpoint. I am writing the whole nuxt.config.js file.

// nuxt.config.js

const webpack = require('webpack')

module.exports = {
  head: {
    title: 'nuxt-client',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: 'Nuxt.js project' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },

  loading: { color: '#3B8070' },

  modules: ['@nuxtjs/auth', '@nuxtjs/axios'],
  
  axios: {
    baseURL: 'http://laravel-server.test/api'
  },
  auth: {
    strategies: {
      local: {
        endpoints: {
          login: { url: 'login', method: 'post', propertyName: 'meta.token' },
          user: { url: 'user', method: 'get', propertyName: 'data' },
          logout: {}
        }
      }
    }
  },
  build: {
    vendor: ['jquery', 'bootstrap'],
    plugins: [
      new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery'
      })
    ],
    extend (config, { isDev, isClient }) {
      if (isDev && isClient) {
        config.module.rules.push({
          enforce: 'pre',
          test: /\.(js|vue)$/,
          loader: 'eslint-loader',
          exclude: /(node_modules)/
        })
      }
    }
  },
  css: ['./node_modules/bootstrap/dist/css/bootstrap.css'],
  plugins: ['~plugins/bootstrap.js']
}

Step 10: Create a login.vue form.

Create a page called login.vue inside pages directory. Write the following code inside it.

// login.vue

<template>
    <div class="container top">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">Login</div>
                    <div class="card-body">
                        <form action="#">
                            <div class="form-group row">
                                <label for="email" class="col-sm-4 col-form-label text-md-right">Email</label>

                                <div class="col-md-6">
                                    <input type="email" class="form-control" required autofocus>
                                        <span class="invalid-feedback" role="alert">
                                            <strong></strong>
                                        </span>
                                </div>
                            </div>

                            <div class="form-group row">
                                <label for="password" class="col-md-4 col-form-label text-md-right">Password</label>

                                <div class="col-md-6">
                                    <input type="password" class="form-control" required>
                                        <span class="invalid-feedback" role="alert">
                                            <strong></strong>
                                        </span>
                                </div>
                            </div>

                            <div class="form-group row mb-0">
                                <div class="col-md-8 offset-md-4">
                                    <button type="submit" class="btn btn-primary">
                                        Login
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    
}
</script>

<style>
.top {
    margin-top: 80px;
}
</style>

Now, go to the layouts >> partials >> Navbar.vue file and add the login route.

// Navbar.js

<li class="nav-item">
   <nuxt-link :to="{ name: 'login' }" class="nav-link">
      Login
   </nuxt-link>
</li>

Switch to the browser and go to this URL: http://localhost:3000/login You can see the form.

Step 11: Submit the login form.

Now, we need to define the data in the form that needs to be submitted on the server. In our case, it is email and password.

// login.vue

data() {
    return {
         userForm: {
            email: '',
            password: ''
         }
     }
},

Also, we need to define the function, when the login button is clicked.

// login.vue

methods: {
   async addUser() {
       await this.$auth.login({
            data: this.userForm
       });
       this.$router.push({
            path: '/'
        });
    }
}

So, our final login.vue file with the html template looks like this.

// login.vue

<template>
    <div class="container top">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">Login</div>
                    <div class="card-body">
                        <form @submit.prevent="addUser">
                            <div class="form-group row">
                                <label for="email" class="col-sm-4 col-form-label text-md-right">Email</label>
                                <div class="col-md-6">
                                    <input type="email" v-model="userForm.email" class="form-control" required autofocus>
                                        <span class="invalid-feedback" role="alert">
                                            <strong></strong>
                                        </span>
                                </div>
                            </div>

                            <div class="form-group row">
                                <label for="password" class="col-md-4 col-form-label text-md-right">Password</label>

                                <div class="col-md-6">
                                    <input type="password" v-model="userForm.password" class="form-control" required>
                                        <span class="invalid-feedback" role="alert">
                                            <strong></strong>
                                        </span>
                                </div>
                            </div>

                            <div class="form-group row mb-0">
                                <div class="col-md-8 offset-md-4">
                                    <button type="submit" class="btn btn-primary">
                                        Login
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            userForm: {
                email: '',
                password: ''
            }
        }
    },
    methods: {
        async addUser() {
            await this.$auth.login({
                data: this.userForm
            });
            this.$router.push({
                path: '/'
            });
        }
    }
}
</script>

<style>
.top {
    margin-top: 80px;
}
</style>

So, if the email and password are correct then it will return a user object as well as the token. You will also redirect to the root route of the nuxt js application and now we need to change the navigation item based on logged in user and logged out user.

Step 12: Create an auth store.

Inside store folder, create one file called auth.js and write the following code.

// auth.js

export const getters = {
    loggedIn (state) {
        return state.loggedIn
    },
    user (state) {
        return state.user
    }
}

We have used @nuxtjs/auth module, which two states.

  1. loggedIn
  2. user

So, if we logged in successfully then we get loggedIn to true. Otherwise, it is false.

Now, we need both of these states globally inside our nuxt.js application. That is why we create a plugin and mixin to access both the store states.

Inside plugins folder, create one folder called mixins and inside that create one file called user.js.

Write the following code inside a user.js file.

// user.js

import Vue from 'vue'
import Vue from 'vue'
import { mapGetters } from 'vuex'

const User = {
    install (Vue, Options) {
        Vue.mixin({
            computed: {
                ...mapGetters({
                    user: 'auth/user',
                    loggedIn: 'auth/loggedIn'
                })
            }
        })
    }
}

Vue.use(User);

Now, register this plugin inside the nuxt.config.js file.

// nuxt.config.js

plugins: ['~plugins/bootstrap.js', '~plugins/mixins/user.js']

Okay, now we replace the Navbar.vue file with the following one.

// Navbar.vue

<template>
    <nav class="navbar navbar-expand-sm bg-light">
        <div class="container">
            <a class="navbar-brand" href="">
                Nuxt Laravel Auth
            </a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false">
                <span class="navbar-toggler-icon"></span>
            </button>

            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav ml-auto">
                    <template v-if="!loggedIn">
                        <li class="nav-item">
                            <nuxt-link :to="{ name: 'login' }" class="nav-link">
                                Login
                            </nuxt-link>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="">Register</a>
                        </li>
                    </template>
                    <template v-if="loggedIn">
                        <li class="nav-item">
                            <a class="nav-link" @click.prevent="logout" href="#">
                                    Logout
                            </a>  
                        </li>
                    </template>
                </ul>
            </div>
        </div>
    </nav>
</template>
<script>
export default {
    
}
</script>

Step 13: Create Register form.

Now, create one page called register.vue inside pages folder and add the following code.

// register.vue

<template>
    <div class="container top">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Register</div>

                <div class="card-body">
                    <form @submit.prevent="registerUser">
                        <div class="form-group row">
                            <label for="name" class="col-md-4 col-form-label text-md-right">Name</label>

                            <div class="col-md-6">
                                <input type="text" class="form-control" v-model="userForm.name" required autofocus>
                                    <span class="invalid-feedback" role="alert">
                                        <strong></strong>
                                    </span>
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="email" class="col-md-4 col-form-label text-md-right">Email</label>

                            <div class="col-md-6">
                                <input type="email" class="form-control" v-model="userForm.email" required>
                                    <span class="invalid-feedback" role="alert">
                                        <strong></strong>
                                    </span>
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="password" class="col-md-4 col-form-label text-md-right">Password</label>
                            <div class="col-md-6">
                                <input type="password" class="form-control" v-model="userForm.password" required>
                                    <span class="invalid-feedback" role="alert">
                                        <strong></strong>
                                    </span>
                            </div>
                        </div>
                        <div class="form-group row mb-0">
                            <div class="col-md-6 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    Register
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</template>

<script>
export default {
    data() {
        return {
            userForm: {
                name: '',
                email: '',
                password: ''
            }
        }
    },
    methods: {
        async registerUser() {
            await this.$axios.post('register', this.userForm);
            this.$auth.login({
                data: {
                    email: this.userForm.email,
                    password: this.userForm.password
                }
            })
            this.$router.push({
                path: '/'
            });
        }
    }
}
</script>

<style>
.top {
    margin-top: 80px;
}
</style>

So, now you can successfully register and logged in to our Nuxt.js application.

Step 14: Create Logout functionality.

At the Laravel server, we need to define the route as well as function to destroy the token.

// api.php

Route::post('/logout', 'Auth\AuthController@logout');

Now, add the logout function inside AuthController.php file.

// AuthController.php 

public function logout()
{
     auth()->logout();
}

Also, we need to define the logout endpoint inside a nuxt.config.js file.

// nuxt.config.js

auth: {
    strategies: {
      local: {
        endpoints: {
          login: { url: 'login', method: 'post', propertyName: 'meta.token' },
          user: { url: 'user', method: 'get', propertyName: 'data' },
          logout: { url: 'logout', method: 'post' }
        }
      }
    }
  },

Add the logout function on client side inside Navbar.vue file.

// Navbar.vue

<template>
    <nav class="navbar navbar-expand-sm bg-light">
        <div class="container">
            <a class="navbar-brand" href="">
                Nuxt Laravel Auth 
            </a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false">
                <span class="navbar-toggler-icon"></span>
            </button>

            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav ml-auto">
                    <template v-if="!loggedIn">
                        <li class="nav-item">
                            <nuxt-link :to="{ name: 'login' }" class="nav-link">
                                Login
                            </nuxt-link>
                        </li>
                        <li class="nav-item">
                            <nuxt-link :to="{ name: 'register' }" class="nav-link">
                                Register
                            </nuxt-link>
                        </li>
                    </template>
                    <template v-if="loggedIn">
                        <li class="nav-item">
                            <a class="nav-link" @click.prevent="logout" href="#">
                                    Logout
                            </a>  
                        </li>
                    </template>
                </ul>
            </div>
        </div>
    </nav>
</template>
<script>
export default {
    methods: {
        logout() {
            this.$auth.logout();
        }
    }
}
</script>

Now, you can log out and it will destroy the token and you will successfully be logged out. You can see your navigation items will be changed to log in and register.

Also, change the pages >> index.vue file to display the current user’s name.

// index.vue

<template>
  <div class="container">
    <p v-if="loggedIn">
      Hello {{ user.name }}
    </p>
    <p v-if="!loggedIn">
      Please sign in
    </p>
  </div>
</template>

<script>

export default {
  
}
</script>

 

Nuxt js authentication

If we logged out then we can see the same page but the text and navigation items will be changed.

 

Vue Laravel Auth

Finally, Nuxt js Laravel Authentication Tutorial is over.

I know there are still so much to add in this project like validation message display at a client side and if the user is logged in then we need to redirect to the home page and not logged in a page if try to access the logged in page, but for this tutorial, it is enough. Already this tutorial is getting big and big. So we will do it in future tutorials.

So we have covered the following things in this Nuxt js Laravel Authentication Tutorial.

  1. Registering the User.
  2. Log in the User.
  3. Display the user information.
  4. Logout the user.

Github Code For Laravel Server

Now, the following code is for the Nuxt.js project.

Github Code For Nuxt.js Client

 

The post Nuxt js Laravel Authentication Tutorial With Example appeared first on AppDividend.

]]>
https://appdividend.com/2018/06/22/nuxt-js-laravel-authentication-tutorial/feed/ 8
Vue Datatable Component Example https://appdividend.com/2018/06/07/vue-datatable-component-example/ https://appdividend.com/2018/06/07/vue-datatable-component-example/#comments Thu, 07 Jun 2018 16:36:09 +0000 http://localhost/wordpress/?p=991 Vue Datatable Example For Client side and Server side

In this tutorial, I will show you Vue Datatable Component Example. For this demo, I am using a vue-tables-2 library.  To send a network request and fetch the data from the server, I am using Axios promise based library. You can find more on Github. I will show you client side datatable implementation. For the server-side implementation of the […]

The post Vue Datatable Component Example appeared first on AppDividend.

]]>
Vue Datatable Example For Client side and Server side

In this tutorial, I will show you Vue Datatable Component Example. For this demo, I am using a vue-tables-2 library.  To send a network request and fetch the data from the server, I am using Axios promise based library. You can find more on Github. I will show you client side datatable implementation. For the server-side implementation of the datatables, you need to have a ready API so that you can query the database.

If you want to learn more about Vue.js then check out this Vue JS 2 – The Complete Guide (incl. Vue Router & Vuex) course.

Vue Datatable Component Example

For this example, we will create a demo server and then fetch the data from that server and feed it to the vuejs. We will see some options to configure the vue datatables. We see first the Client side datatable, and then we will go for server side datatable.

Dependencies

  • Vue.js (>=2.0)
  • Server Side: axios OR vue-resource (>=0.9.0) OR jQuery for the AJAX requests

I am using Axios, but you can use any above-mentioned libraries.

Compatibility

  • Vuex (>=2.0)
  • Bootstrap 3 / Bootstrap 4 / Bulma

I am using Bootstrap 4 for this example.

Step 1: Install Vue.js using Vue CLI.

First of all, let us install Vue CLI and then create a new Vue project. Type the command.

npm install -g @vue/cli
# or
yarn global add @vue/cli

Okay, now create a Vue.js project using this command.

vue create vuedatatable

Now go to the project folder.

cd vuedatatable

Open project in the editor. I am using VSCode.

code .

Start the dev server using this command.

npm run serve

Step 2: Configure backend server.

For this first demo, I am using json-server. Let us install the package using node package manager.

yarn global add json-server

# or

npm install -g json-server

Now, inside the root of the project, create one folder called data and inside that create one file called db.json.

Write the following code inside a db.json file.

{
    "songs": [
    {
        "id": "1",
        "name": "Thriller",
        "album": "Thriller"
    },
    {
        "id": "2",
        "name": "Dangerous",
        "album": "Dangerous"
    },
    {
        "id": "3",
        "name": "Stranger In Moscow",
        "album": "History"
    },
    {
        "id": "4",
        "name": "Smooth Criminal",
        "album": "BAD"
    },
    {
        "id": "5",
        "name": "BAD",
        "album": "BAD"
    },
    {
        "id": "6",
        "name": "Black or White",
        "album": "Dangerous"
    },
    {
        "id": "6",
        "name": "You rock My World",
        "album": "Invincible"
    },
    {
        "id": "7",
        "name": "Hold My Hand",
        "album": "Michael"
    },
    {
        "id": "8",
        "name": "Rock With You",
        "album": "Off The Wall"
    },
    {
        "id": "9",
        "name": "Billy Jean",
        "album": "Thriller"
    },
    {
        "id": "10",
        "name": "They don't really care about us",
        "album": "History"
    }
  ]
}

So, this data will be served by json-server. The form of the data is JSON, so it is easy to feed the data to the Vue.js application.

Now, start the JSON server using the following command.

json-server --watch data/db.json --port 4000

Now, go to this URL: http://localhost:4000 It will serve as a JSON data.

Step 3: Install Axios and vue-axios.

Go to the CMD and type this command.

npm install vue-axios axios --save

Register these packages inside src >> main.js file.

// main.js

import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)

Vue.config.productionTip = false

new Vue({
  render: h => h(App)
}).$mount('#app')

Step 4: Make component inside components folder.

Inside src >> components folder, create a file called VueDataTable.vue file.

// VueDataTable.vue

<template>
  <div>
    DataTable
  </div>
</template>

<script>
export default {

}
</script>

Now, import this component inside src >> App.vue file.

// App.vue

<template>
  <div id="app">
    <vue-data-table></vue-data-table>
  </div>
</template>

<script>
import VueDataTable from './components/VueDataTable'

export default {
  name: 'app',
  components: {
    VueDataTable
  }
}
</script>

Step 5: Install Bootstrap 4 library.

Type the following command to install the  Bootstrap 4.

npm install bootstrap --save

Import bootstrap.min.css file inside main.js file.

// main.js

import '../node_modules/bootstrap/dist/css/bootstrap.min.css'

Step 6: Install vue-tables-2 library.

Type the following command to install the vue-tables-2 library.

npm install vue-tables-2 --save

Next step is to register vue-tables-2 inside a main.js file. I am showing the whole main.js file.

// main.js

import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
import { ClientTable } from 'vue-tables-2';

Vue.use(ClientTable);

Vue.use(VueAxios, axios)

Vue.config.productionTip = false

import '../node_modules/bootstrap/dist/css/bootstrap.min.css'

new Vue({
  render: h => h(App)
}).$mount('#app')

Right now, I am just using a ClientTable module.

Step 7: Send an Axios GET request.

Okay, now we need to send a GET request to the json-server and fetch the data.

So, when the VueDataTable.vue component mounted, then we send a request and fetch the data. Then that fetched data assign to the local variable and display it inside vue-client-table.

// VueDataTable.vue

<template>
  <div class="container">
      <v-client-table 
          :data="tableData"
          :columns="columns" 
          :options="options">
      </v-client-table>
  </div>
</template>

<script>

export default {
    data() {
        return {
            columns: ['id', 'name', 'album'],
            tableData: [],
            options: {
                headings: {
                    id: 'ID',
                    name: 'Song Name',
                    album: 'Album'
                },
                sortable: ['name', 'album'],
                filterable: ['name', 'album']
            }
        }
    },
    mounted() {
        this.axios.get('http://localhost:4000/songs').then(res => {
            this.tableData = res.data
        })
    }
 
}
</script>

<style>
#app {
  width: 95%;
  margin-top: 50px; 
}

.VuePagination {
  text-align: center;
}

.vue-title {
  text-align: center;
  margin-bottom: 10px;
}

.vue-pagination-ad {
  text-align: center;
}

.glyphicon.glyphicon-eye-open {
  width: 16px;
  display: block;
  margin: 0 auto;
}

th:nth-child(3) {
  text-align: center;
}

.VueTables__child-row-toggler {
  width: 16px;
  height: 16px;
  line-height: 16px;
  display: block;
  margin: auto;
  text-align: center;
}

.VueTables__child-row-toggler--closed::before {
  content: "+";
}

.VueTables__child-row-toggler--open::before {
  content: "-";
}

</style>

Save the file and go to the http://localhost:8080/

You can see that our Client side Datatable is working correctly.

Vue Datatable Component Example

 

You can do the following things with Datatable.

  1. Searching
  2. Sorting
  3. Pagination

So almost all the functionalities that the general data tables are providing are including in this example.

Explanation

First, for our component, we have taken 3 data properties.

  1. columns
  2. tableData
  3. options

Columns property defines, which columns are we need to display from the backend.

The tableData is property defines as actual data from the backend. It is an array that contains the whole data.

The options are an object that contains the various configuration for our DataTable.

You can find more on options in this link.

Server-side DataTable

On server side DataTable, you need to send a GET request to the server with the Parameters and then get a response.

Let us change the db.json file to meet the requirement of the <v-server-table> data.

{
    "songs": {
        "data" : [
    {
        "id": "1",
        "name": "Thriller",
        "album": "Thriller"
    },
    {
        "id": "2",
        "name": "Dangerous",
        "album": "Dangerous"
    },
    {
        "id": "3",
        "name": "Stranger In Moscow",
        "album": "History"
    },
    {
        "id": "4",
        "name": "Smooth Criminal",
        "album": "BAD"
    },
    {
        "id": "5",
        "name": "BAD",
        "album": "BAD"
    },
    {
        "id": "6",
        "name": "Black or White",
        "album": "Dangerous"
    },
    {
        "id": "6",
        "name": "You rock My World",
        "album": "Invincible"
    },
    {
        "id": "7",
        "name": "Hold My Hand",
        "album": "Michael"
    },
    {
        "id": "8",
        "name": "Rock With You",
        "album": "Off The Wall"
    },
    {
        "id": "9",
        "name": "Billy Jean",
        "album": "Thriller"
    },
    {
        "id": "10",
        "name": "They don't really care about us",
        "album": "History"
    }
],
    "count": "11"
    }
}

The return response must have two properties.

  1. data
  2. count

In a real-time scenario, the data is coming from a backend server, but for this example, I am changing the JSON object manually to show the server-side table.

Now, first change the main.js file and import the ServerTable module.

// main.js

import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
import { ServerTable } from 'vue-tables-2';

Vue.use(ServerTable);

Vue.use(VueAxios, axios)

Vue.config.productionTip = false

import '../node_modules/bootstrap/dist/css/bootstrap.min.css'

new Vue({
  render: h => h(App)
}).$mount('#app')

Okay, now we can write the code inside VueDataTable.vue file.

// VueDataTable.vue

<template>
  <div class="container">
      <v-server-table
          :columns="columns" 
          :options="options">
      </v-server-table>
  </div>
</template>

<script>

export default {
    data() {
        return {
            columns: ['id', 'name', 'album'],
            options: {
                headings: {
                    id: 'ID',
                    name: 'Song Name',
                    album: 'Album'
                },
                sortable: ['name', 'album'],
                filterable: ['name', 'album'],
                requestFunction: function () {
                    return this.axios.get('http://localhost:4000/songs').catch(function (e) {
                        this.dispatch('error', e);
                    }.bind(this));
                },
                responseAdapter: function(resp) {
                  return {
                    data: resp.data.data,
                    count: resp.data.count
                  }
                }
            }
        }
    }
}
</script>

<style>
#app {
  width: 95%;
  margin-top: 50px; 
}

.VuePagination {
  text-align: center;
}

.vue-title {
  text-align: center;
  margin-bottom: 10px;
}

.vue-pagination-ad {
  text-align: center;
}

.glyphicon.glyphicon-eye-open {
  width: 16px;
  display: block;
  margin: 0 auto;
}

th:nth-child(3) {
  text-align: center;
}

.VueTables__child-row-toggler {
  width: 16px;
  height: 16px;
  line-height: 16px;
  display: block;
  margin: auto;
  text-align: center;
}

.VueTables__child-row-toggler--closed::before {
  content: "+";
}

.VueTables__child-row-toggler--open::before {
  content: "-";
}

</style>

So, first, I have implemented my request function to fetch the server data.

We need to pass some parameters to get all functionalities, but right now I am just displaying the data.

In this example, remember Sorting, Searching, and Pagination will not work because this is a server-side table and we need to send a request with the parameter to get the desired data.

I have just implemented the code to fetch the data. Also, I have used the responseAdapter function to format the client specific data.

You get the idea right; if you want to build fully functional server-side datatable then you have a backend that responds every time, you send a request.

In client side, it is not needed because all the calculation is done on client side, so only one time you need to send a request, and you are done.

Finally, Vue Datatable Component Example is over. Thanks for taking.

The post Vue Datatable Component Example appeared first on AppDividend.

]]>
https://appdividend.com/2018/06/07/vue-datatable-component-example/feed/ 3
Vue Notification Tutorial https://appdividend.com/2018/06/05/vue-notification-tutorial/ https://appdividend.com/2018/06/05/vue-notification-tutorial/#comments Tue, 05 Jun 2018 20:22:09 +0000 http://localhost/wordpress/?p=980 Vue Notification Toast Example

Vue Notification Tutorial is the today’s main topic. In this example, I have used Vue Toasted One of the Best Toast plugin available for VueJS. It is responsive, touch compatible, easy to use, attractive and feature rich with icons, actions, etc. In this demo, when we save any data in the database, we will display a […]

The post Vue Notification Tutorial appeared first on AppDividend.

]]>
Vue Notification Toast Example

Vue Notification Tutorial is the today’s main topic. In this example, I have used Vue Toasted One of the Best Toast plugin available for VueJS. It is responsive, touch compatible, easy to use, attractive and feature rich with icons, actions, etc. In this demo, when we save any data in the database, we will display a notification saying that item has successfully saved or if we show any error then we can show it. For the backend, we use Laravel PHP Framework.

If you want to learn more about Vue.js then check out this Vue JS 2 – The Complete Guide (incl. Vue Router & Vuex) course.

Vue Notification Tutorial

As always, we can start our project by installing the Vue.js.

Step 1: Install Vue.js using Vue CLI.

Type the following command to install Vue CLI globally.

npm install -g @vue/cli
# or
yarn global add @vue/cli

Okay, now create a Vue.js project using the following command.

vue create vuenotify

 

Vue Notification Tutorial

Go into the project folder and open in your IDE.

cd vuenotify
code .

Step 2: Install Bootstrap 4.

Install the Bootstrap 4 using the following command.

npm install bootstrap --save

Now, import the bootstrap.min.css file inside src >> main.js file.

// main.js

import Vue from 'vue'
import App from './App.vue'

import '../node_modules/bootstrap/dist/css/bootstrap.min.css'

Vue.config.productionTip = false

new Vue({
  render: h => h(App)
}).$mount('#app')

Step 3: Create a Form to enter the data.

For this example, I am taking simple two fields 1) Name 2) Email.

Now, inside components folder, create one component called ItemForm.vue.

// ItemForm.vue

<template>
    <div class="container">
        <div class="card">
            <div class="card-header">
                <h3>Add Item</h3>
            </div>
            <div class="card-body">
                <form @submit.prevent="addItem">
                    <div class="form-group">
                        <label>Name:</label>
                        <input type="text" class="form-control" v-model="item.name"/>
                    </div>
                    <div class="form-group">
                        <label>Price:</label>
                        <input type="text" class="form-control" v-model="item.price"/>
                    </div>
                    <div class="form-group">
                        <input type="submit" class="btn btn-primary" value="Add"/>
                    </div>
                </form>
            </div>
        </div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            item: {}
        }
    },
    methods: {
        addItem() {
            
        }
    } 
}
</script>

Now, import ItemForm.vue component inside src >> App.vue file.

// App.vue

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

<script>
import ItemForm from './components/ItemForm.vue'

export default {
  name: 'app',
  components: {
    ItemForm
  }
}
</script>

Step 4: Install Axios To Send A Post Request.

Type the following command to install axios and vue-axios.

npm install vue-axios axios --save

Now, configure inside src >> main.js fiie.

// main.js

import Vue from 'vue'
import App from './App.vue'

import VueAxios from 'vue-axios'
import axios from 'axios'

Vue.use(VueAxios, axios)

import '../node_modules/bootstrap/dist/css/bootstrap.min.css'

Vue.config.productionTip = false

new Vue({
  render: h => h(App)
}).$mount('#app')

Okay, now we can send a POST request to the Laravel server and save the data in the database.

Now, we can write the code inside addItem() function of the ItemForm.vue file.

// ItemForm.vue

methods: {
   addItem() {
      let uri = 'http://notify.test/api/item/create';
      this.axios.post(uri, this.item).then((response) => {
          console.log(response.data);
      });
   }
}

Till now, I have not created Laravel API; I will do it in next step.

Step 5: Install Laravel 5.6.

I am using Laravel Valet, so I am installing Laravel using the following command.

laravel new notify

Set up MySQL database in the .env file.

Next step is to create a model and migration file using the following command.

php artisan make:model Item -m

Write the following schema inside a create_items_table.php file.

// create_items_table

public function up()
{
    Schema::create('items', function (Blueprint $table) {
       $table->increments('id');
       $table->string('name');
       $table->integer('price');            
       $table->timestamps();
    });
}

Type the following command.

php artisan migrate

It will create the tables in the database. I am using MySQL database.

Step 6: Create controller and routes in an api.php.

Okay, now create the ItemController.

php artisan make:controller ItemController

Create the route inside routes >> api.php file.

// api.php

Route::post('item/create', 'ItemController@store');

Now, code the store function inside ItemController.php file.

// ItemController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Item;

class ItemController extends Controller
{
    public function store(Request $request)
    {
        $item = new Item;
        $item->name = $request->get('name');
        $item->price = $request->get('price');

        $item->save();

        return response()->json(['success' =>'Your data is successfully saved'],200);
    }
}

Now, still we are missing the one thing, and that is CORS issue.

Step 7: Solve CORS Issue.

Install the package using the below command.

 composer require barryvdh/laravel-cors

Now, we need to publish the package using the following command.

php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"

Finally, add the following line inside app >> Http >> Kernel.php file.

We are adding middleware on the part of the API so that you can write the following code.

// Kernel.php

'api' => [
      'throttle:60,1',
      'bindings',
      \Barryvdh\Cors\HandleCors::class,
],

Okay, now if you have not started the Vue development server then start the server using the following command.

npm run serve

Now, try to save the item in the database, and it will save successfully, and you can see in the console.

Step 8: Install vue-toasted library.

Install it via NPM.

npm install vue-toasted --save

Now, register the package inside the main.js file.

// main.js

import Toasted from 'vue-toasted'
Vue.use(Toasted, {
  duration: 1000
})

Here, I have passes option as a time duration. You can pass the actual object that contains different properties.

You can also add the link inside toast so that you can cancel that toast. You can use it like this.

// main.js

Vue.use(Toasted, {
  duration: 9000,
  action : {
    text : 'Cancel',
    onClick : (e, toastObject) => {
        toastObject.goAway(0);
    }
  }
})

You can find more API on here

Now, you can use the toast inside the ItemForm.vue component.

// ItemForm.vue

methods: {
   addItem() {
       let uri = 'http://notify.test/api/item/create';
       this.axios.post(uri, this.item).then((response) => {
          this.$toasted.show(response.data.success);
      });
   }
}

So, finally, Vue Notification Tutorial Example From Scratch is over. Thanks for taking.

The post Vue Notification Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2018/06/05/vue-notification-tutorial/feed/ 1