Vue js – AppDividend https://appdividend.com Latest Code Tutorials Sat, 29 Dec 2018 06:55:38 +0000 en-US hourly 1 https://wordpress.org/?v=5.2.3 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png Vue js – 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/ 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
Getting Started With Axios Promise Based HTTP Client Tutorial Example https://appdividend.com/2018/08/30/getting-started-with-axios-tutorial-example/ https://appdividend.com/2018/08/30/getting-started-with-axios-tutorial-example/#comments Thu, 30 Aug 2018 13:31:52 +0000 http://localhost/wordpress/?p=1583 Axios Example Tutorial From Scratch

Getting Started With Axios Promise Based HTTP Client Tutorial Example is today’s leading topic. Axios is the Promise based HTTP client for the browser and node.js.  It supports all modern browsers, including support for IE8 and higher. It is promise-based, and this lets us write async/await code to perform XHR requests very quickly. Using Axios, It is effortless to send an asynchronous […]

The post Getting Started With Axios Promise Based HTTP Client Tutorial Example appeared first on AppDividend.

]]>
Axios Example Tutorial From Scratch

Getting Started With Axios Promise Based HTTP Client Tutorial Example is today’s leading topic. Axios is the Promise based HTTP client for the browser and node.js.  It supports all modern browsers, including support for IE8 and higher. It is promise-based, and this lets us write async/await code to perform XHR requests very quickly. Using Axios, It is effortless to send an asynchronous HTTP request to the server or REST endpoints and perform any CRUD operations. An Axios library can be used in your everyday JavaScript application or can be used together with more advanced frameworks like Vue.js, Angular, or Node.js.Getting Started With Axios Tutorial Example will teach you how to use Axios to send a POST request to the server or send GET request to fetch the data.

If you want to learn more about the latest Javascript tutorials then check out this The Complete Javascript Course 2018.

Axios has lots of advantages over the native Fetch API:

  • It supports older browsers (Fetch needs a polyfill)
  • It has as a way to abort a request.
  • It has a way to set a response timeout.
  • It has built-in CSRF protection.
  • It supports upload progress.
  • It performs automatic JSON data transformation.
  • It works with Node.js very well.

In this tutorial, you’ll learn how to install and add Axios to your project and perform an asynchronous HTTP request. We’ll cover a real-world scenario throughout this example.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Join the program

Getting Started With Axios

We will use Axios with Node.js.

Okay, first create one folder called axios-prac by the following command.

mkdir axios-prac
cd axios-prac

Now, we need to create the package.json file. So let us build using the following command.

npm init -y

 

Getting Started With Axios Promise Based HTTP Client Tutorial Example

#1: Install Axios HTTP Library.

Now, we need to install an axios library. We can install it using the npm or yarn.

npm install axios --save

# or

yarn add axios

 

Axios POST Tutorial Example

#2: Create the server.js file.

Inside the root folder, create one file called server.js.

Now, we send an HTTP request using Axios to GitHub api server and try to fetch the data. So let us add the following code inside the server.js file.

// server.js

const axios = require('axios');

async function getGithubData() {
  let res = await axios.get('https://api.github.com/users/KrunalLathiya');
  console.log(res.data.login);
}

getGithubData();

Here, also we have used an async-await feature of ES7. Save the file and go to the terminal or CMD and type the following command to run the node server.

node server

You can see that my name has printed that means, we have successfully sent an HTTP Request using Axios.

So, this is how anyone can use Axios with Node.js. It is effortless. It is the primary example of Axios API. Let us dive into Axios and get more details.

#The Axios Api

You can start an HTTP request from the axios object:

If you are using plain JS, then you can use axios using the following code.

axios({
  url: 'https://api.github.com/users/KrunalLathiya',
  method: 'get'
})

But generally, we do not use the above syntax. Instead, we can use the following syntax.

axios.get()
axios.post()

Axios offers methods for all the HTTP verbs, which are less popular but still used:

  1. axios.put()
  2. axios.delete()
  3. axios.patch()
  4. axios.options()
  5. axios.head()

If we do not want to use async-await and make use of the promise to resolve the response, then we can write the following code.

// server.js

const axios = require('axios');

function getGithubData() {
  axios.get('https://api.github.com/users/KrunalLathiya')
    .then(res => {
      console.log(res.data.login);
    });
}

getGithubData();

We will get the same result, but we have used promise to resolve the request and get the data.

If the promise does not resolve, it will be rejected, and we can get an error in the catch block.

// server.js

const axios = require('axios');

function getGithubData() {
  axios.get('https://api.github.com/users/KrunalLathiya')
    .then(res => {
      console.log(res.data.login);
    })
    .catch(err => {
      console.log(err);
    });
}

getGithubData();

We can also pass the parameter to the Axios GET Request. The syntax for that is following.

axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });

#Axios Request Config/Options

If we need to set up the global config, then we can write the following code inside JS file.

axios.defaults.headers.post['header1'] = 'value' // for POST requests
axios.defaults.headers.common['header1'] = 'value' // for all requests

We can send a GET request with the Authorization Token. Let us say we need to add the JWT token in the request then we can write the following object with the request. The following code is the syntax.

axios.get('https://appdividend.com', {
 headers: {
   Authorization: 'Bearer ' + token //the token is a variable which holds the token
 }
});

If we are working with the POST request, then we can also add the config object like the following code.

let config = {
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  responseType: 'blob'
};

axios.post('https://appdividend.com', data, config)
     .then((response) => {
        console.log(response.data);
});

So, here we have passed the three parameters in the axios post request.

  1. URL (Where we need to send an HTTP request).
  2. Data (That needs to be posted and saved in the database).
  3. Request object.

So, you can pass the following options in the request.

  • baseUrl: if you specify a base URL, it’ll be prepended to any relative URL you use.
  • headers: It is an object of key-value pairs to be sent as headers.
  • params: an object of key/value pairs that will be serialized and appended to the URL as a query string.
  • responseType: if we want to get the response in a format other than JSON then we can set this property to arraybufferblobdocumenttext, or stream.
  • auth: Auth option is used when we need to pass an object with the username and password credentials for HTTP Basic authentication on the request.

#Axios Response Object

When the HTTP request is successful sent, than then() callback will receive a response object with the following properties:

  • data: the payload returned from the server. By default, Axios expects JSON and will parse this back into a JavaScript object for you.
  • status: the HTTP code returned from the server.
  • statusText: the HTTP status message returned by the server.
  • headers: all the headers sent back by the server.
  • config: the original request configuration.
  • request: the actual XMLHttpRequest object (when running in a browser).

#Axios error object

If there is any problem with the axios request, the promise will be rejected with an error object containing the following properties:

  • message: the error message text.
  • response: the response object (if received) as described in the previous section.
  • request: the actual XMLHttpRequest object (when running in a browser).
  • config: the original request configuration.

#Axios Post Request

Performing a POST request is just like making a GET request, but instead of axios.get(), you use axios.post():

An object containing the POST parameters is the second argument:

axios.post('https://appdividend.com', {
  foo: 'bar'
})

#Axios Interceptors

We can intercept the request or response at some given point of time like while sending a request or while receiving the response object. Axios also allows us to add functions called interceptors. Like transforms, these interceptor functions can be attached to fire when a request is made, or when a response is received.

// Add a request interceptor
axios.interceptors.request.use((config) => {
    // Do something before request is sent
    return config;
  }, (error) => {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use((response) => {
    // Do something with response data
    return response;
  }, (error) => {
    // Do something with response error
    return Promise.reject(error);
  });

#Multiple Axios Requests simultaneously.

To execute multiple requests in parallel, provide an array argument to axios.all(). When all requests are complete, you’ll receive an array containing the response objects in the same order they were sent. Alternatively, you can use axios spread to spread the array into multiple arguments. The spread is preferred since dealing with array indexes could be misleading.

// Requests will be executed in parallel...
axios.all([
    axios.get('https://api.github.com/users/codeheaven-io');
    axios.get('https://api.github.com/users/codeheaven-io/repos')
  ])
  .then(axios.spread(function (userResponse, reposResponse) {
    //... but this callback will be executed only when both requests are complete.
    console.log('User', userResponse.data);
    console.log('Repositories', reposResponse.data);
  }));

#Third-party Add-ons

Axios can benefit from an ecosystem of third-party libraries that extend its functionality. From interceptors to testing adaptors to loggers, there’s quite a variety available. Here are a few that I think you may find useful:

  • axios-mock-adaptor: It allows you to easily mock requests to facilitate testing your code.
  • axios-cache-plugin: It is a wrapper for selectively caching GET requests.
  • redux-axios-middleware: If you’re a Redux user, this middleware provides a neat way to dispatch Ajax requests with open old actions.

Finally, Getting Started With Axios Promise Based HTTP Client Tutorial Example is over. Thanks for taking.

The post Getting Started With Axios Promise Based HTTP Client Tutorial Example appeared first on AppDividend.

]]>
https://appdividend.com/2018/08/30/getting-started-with-axios-tutorial-example/feed/ 3
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/#comments 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/ 1
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/#comments 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/ 1
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
Laravel and Vue Example | Build a twitter type web application https://appdividend.com/2018/06/11/laravel-and-vue-example-tutorial/ https://appdividend.com/2018/06/11/laravel-and-vue-example-tutorial/#comments Mon, 11 Jun 2018 17:08:03 +0000 http://localhost/wordpress/?p=1021 Laravel and Vue.js Tutorial with Example From Scratch

In this Laravel and Vue Example, we will build a twitter type web application. For this tutorial, I am using Laravel and Vue.js. I am defining some components inside Vue.js. Also, I am using Axios to send a network request. We simply build an application in which, the user can post the tweet and appears in […]

The post Laravel and Vue Example | Build a twitter type web application appeared first on AppDividend.

]]>
Laravel and Vue.js Tutorial with Example From Scratch

In this Laravel and Vue Example, we will build a twitter type web application. For this tutorial, I am using Laravel and Vue.js. I am defining some components inside Vue.js. Also, I am using Axios to send a network request. We simply build an application in which, the user can post the tweet and appears in his timeline. Also, one user can follow or unfollow each other. If currently signed in user follow any other registered user then he can also see the following user’s tweet in his timeline. The very basic app, but the very powerful web app to understand laravel and vue.js fundamental concepts.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Check out this amazing program

Laravel and Vue Example

Install Laravel 5.6 and its NPM dependencies.

Step 1: Install and configure Laravel.

Type the following command in the terminal.

laravel new laratwitter

Go to the folder.

cd laratwitter

Install the front-end dependencies using the following command.

npm install

Now, configure the database inside the .env file.

Create an authentication using the following command.

php artisan make:auth

Migrate all the tables in the database using the following command.

php artisan migrate

Register one user on this URL: http://laratwitter.test/register

Next step is to modify the resources >> views >> home.blade.php file.

We need to add two things in that page.

  1. Tweet Form
  2. Timelines
@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-4">
            Tweet Form
        </div>
        <div class="col-md-8">
            TimeLines
        </div>
    </div>
</div>
@endsection

Okay, now go to this URL: http://laratwitter.test/home and you can see the changes.

Step 2: Create a Tweet Form.

We are using Vue.js. So let us create a component called FormComponent.vue inside resources >> assets >> js >> components folder.

Write the following code inside FormComponent.vue file.

// FormComponent.vue

<template>
    <div class="col-md-4">
        <form>
            <div class="form-group">
                <textarea 
                    class="form-control" 
                    rows="8" cols="8" 
                    maxlength="130" 
                    required>
                </textarea>
            </div>
            <div class="form-group">
                <button class="btn btn-primary">
                    Tweet
                </button>
            </div>
        </form>        
    </div>
</template>
<script>
export default {
    
}
</script>

Import this component inside resources >> assets >> js >> app.js file.

// app.js

require('./bootstrap');

window.Vue = require('vue');

Vue.component('form-component', require('./components/FormComponent.vue'));

const app = new Vue({
    el: '#app'
});

Also, we need to add this component inside a home.blade.php file.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
       <form-component></form-component>
        <div class="col-md-8">
            TimeLines
        </div>
    </div>
</div>
@endsection

Now, refresh the webpage, and you can see the form component rendered inside blade file.

Step 3: Create a Post model and migration.

Okay, now create a model and migration.

php artisan make:model Post -m

Write the following schema inside a create_posts_table.php file.

// create_posts_table

public function up()
{
   Schema::create('posts', function (Blueprint $table) {
       $table->increments('id');
       $table->integer('user_id')->unsigned();
       $table->string('body', 130);
       $table->timestamps();

       $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}

Migrate the posts table.

php artisan migrate

You can see that the posts table is created in the MySQL database.

Also, we need to create a PostController. So create a controller by the following command.

php artisan make:controller PostController

Step 4: Define the relationships.

Inside User.php model, we need to define a function that is a relationship between Post model and User model.

Want to learn to code, gain a new skill and get a new job. Check out this amazing program
// User.php

public function posts()
{
   return $this->hasMany(Post::class);
}

Also, the Post belongs to User. So we can define the inverse relationship inside Post.php model.

// Post.php

public function user()
{
   return $this->belongsTo(User::class);
}

Step 5: Saving the Tweet in the database.

When we have used the command npm install, it has already install axios library. So we can use the axios to send a POST request to a Laravel backend web server and store the tweet in the database.

But first, let us define the route. So set the route inside routes >> web.php file.

// web.php

Route::post('tweet/save', 'PostController@store');

Also, we need to define the $fillable property inside Post.php model to prevent the Mass Assignment Exception.

<?php

// Post.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{

    protected $fillable = ['user_id', 'body'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

The final thing is to define the store function inside PostController.php file.

<?php

namespace App\Http\Controllers;

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

class PostController extends Controller
{
    public function store(Request $request, Post $post)
    {
        $newPost = $request->user()->posts()->create([
            'body' => $request->get('body')
        ]);
   
        return response()->json($post->with('user')->find($newPost->id));
    }
}

I have used the relationship to save the Post data, and it automatically adds the current logged in user’s id inside user_id column on every saved post.

Also, we need to use axios library to send a POST request, so write the code inside FormComponent.vue file.

// FormComponent.vue

<template>
    <div class="col-md-4">
        <form @submit.prevent="saveTweet">
            <div class="form-group">
                <textarea 
                    class="form-control" 
                    rows="8" cols="8" 
                    maxlength="130"
                    v-model="body"
                    required>
                </textarea>
            </div>
            <div class="form-group">
                <button class="btn btn-primary">
                    Tweet
                </button>
            </div>
        </form>        
    </div>
</template>
<script>
export default {
    data() {
        return {
            body: ''
        }
    },
    methods: {
        saveTweet() {
            axios.post('/tweet/save', {body: this.body}).then(res => {
                console.log(res.data);
            }).catch(e => {
                console.log(e);
            });
            
        }
    }
}
</script>

CSRF_TOKEN will be included by default inside every POST request, so we do need to add manually. Now, if everything is setup correctly then you can be able to save the Post and in response, you get the Post object with its associated user.

Laravel and Vue Example Build a twitter type web application

 

Step 6: Create a vue event.

To display all the tweets on the frontend, we need to first show the tweets to the Timeline, and for that, we need to create an event. Remember, we are not refreshing the page to fetch all the tweets. When we add a new tweet, we need to display that tweet in the user’s timeline without refresh the page. 

So, for that, we create an Event and then fire that event. 

That fired event listen by Timeline component and update the UI according to it.

We can also use Vuex for this, but right now, we are not diving into Stores and actions, let us keep it simple.

Inside resources >> assets >> js folder, create one js file called event.js. Write the following code inside it.

// event.js

import Vue from 'vue';

export default new Vue();

Now, import this file inside FormComponent.vue file.

// FormComponent.vue

<template>
    <div class="col-md-4">
        <form @submit.prevent="saveTweet">
            <div class="form-group">
                <textarea 
                    class="form-control" 
                    rows="8" cols="8" 
                    maxlength="130"
                    v-model="body"
                    required>
                </textarea>
            </div>
            <div class="form-group">
                <button class="btn btn-primary">
                    Tweet
                </button>
            </div>
        </form>        
    </div>
</template>
<script>
import Event from '../event.js';
export default {
    data() {
        return {
            body: '',
            postData: {}
        }
    },
    methods: {
        saveTweet() {
            axios.post('/tweet/save', {body: this.body}).then(res => {
                this.postData = res.data;
                Event.$emit('added_tweet', this.postData);
            }).catch(e => {
                console.log(e);
            });
            this.body = '';
        }
    }
}
</script>

So, when the new post is saved, we can emit an event that has the saved tweet with the user.

Here, we are emitting the newly saved post with an event, so that listener can catch that data and update the UI with that data.

Step 7: Create a Timeline Component.

Now, we need to create second vue component called TimelineComponent.vue inside resources >> assets >> js >> components folder. Write the following code inside TimelineComponent.vue file.

// TimelineComponent.vue

<template>
    <div class="col-md-8 posts">
        <p v-if="!posts.length">No posts</p>
        <div class="media" v-for="post in posts" :key="post.id">
            <img class="mr-3" />
            <div class="media-body">
                <div class="mt-3">
                    <a href="#">{{ post.user.name }}</a>
                </div>
                <p>{{ post.body }}</p>
            </div>
        </div>
    </div>
</template>
<script>
import Event from '../event.js';

export default {
    data() {
        return {
            posts: [],
            post: {}
        }
    },
    mounted() {
        Event.$on('added_tweet', (post) => {
            this.posts.unshift(post);
        });
    }
}
</script>

So, we are listening for that event, and when the event is listened by this component, we add the new data to the posts array and iterate the component to display the tweet and user as well.

Now, register this component inside an app.js file.

// app.js

Vue.component('timeline-component', require('./components/TimelineComponent.vue'));

Also, add this component inside a home.blade.php file.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <form-component></form-component>
        <timeline-component></timeline-component>
    </div>
</div>
@endsection

Save the file and go to the: http://laratwitter.test/home.

Add a new tweet, and you can see the name and tweet.

Step 8: Show time in the timeline.

We need to append one attribute inside Post.php model to get the time.

So, we can use the append attribute to add the time data and then fetch it in the response. Very simple.

// Post.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{

    protected $fillable = ['user_id', 'body'];

    protected $appends = ['createdDate'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function getCreatedDateAttribute()
    {
        return $this->created_at->diffForHumans();
    }

}

Now, we can access the createdDate property inside TimelineComponent.vue file.

<div class="mt-3">
   <a href="#">
     {{ post.user.name }}
   </a> | {{ post.createdDate }}
</div>

Now, refresh the page, add the tweet, and you can see something like 1 second ago.

Step 9: Create a user profile.

We use Route Model Binding to display the user profile. We create a link based on the user’s name. Generally, we use the username for this, so that we can get unique URL, but for this demo, I am using the name for the unique URL.

Also, we need to add the unique property inside RegisterController.php file, so that we can build the user profile link unique.

// RegisterController.php

protected function validator(array $data)
{
   return Validator::make($data, [
      'name' => 'required|string|max:255|unique:users',
      'email' => 'required|string|email|max:255|unique:users',
      'password' => 'required|string|min:6|confirmed',
   ]);
}

Now, we need to create one controller called UserController. Type the following command.

php artisan make:controller UserController

Now, add the following function inside UserController.php file.

<?php

// UserController.php

namespace App\Http\Controllers;

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

class UserController extends Controller
{
    public function show(User $user)
    {
        return view('user', compact('user'));
    }
}

Here, I am using Route Model Binding, but we will use my name on the route. So, we can access it through user’s name key. So we need to define the routing key inside User.php file.

// User.php

public function getRouteKeyName()
{
   return 'name';
}

Create a view file called user.blade.php inside views folder.

<!-- user.blade.php -->

@extends('layouts.app')

@section('content')
<div class="container">
    {{ $user->name }}
</div>
@endsection

Also, we need to define the route inside a web.php file.

// web.php

<?php

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');
Route::post('tweet/save', 'PostController@store');

Route::get('users/{user}', 'UserController@show')->name('user.show');

Let us say; I have registered the user with a name: krunal.

We can access its profile using this URL:http://laratwitter.test/users/krunal

When we hit that URL, we can see the profile page is appearing. So till now, we have done all correctly.

Step 10: Display URL inside TimelineComponent.

Generally, when we need a data that is created from another data from the same table, we do not need to store that data, we append that data in that model object while fetching it.

We can same do the thing here, the profile url is based on the name, so we can append one new data called profileUrl and then append to it inside User.php model.

Create an accessor for a profileLink inside User.php model file.

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

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

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

    protected $appends = ['profileLink'];

    public function posts()
    {
        return $this->hasMany(Post::class);
    }

    public function getRouteKeyName()
    {
        return 'name';
    }

    public function getProfileLinkAttribute()
    {
        return route('user.show', $this);
    }

}

Now, we can display this URL inside TimelineComponent.vue file.

// TimelineComponent.vue

<template>
    <div class="col-md-8 posts">
        <p v-if="!posts.length">No posts</p>
        <div class="media" v-for="post in posts" :key="post.id">
            <img class="mr-3" />
            <div class="media-body">
                <div class="mt-3">
                    <a :href="post.user.profileLink">{{ post.user.name }}</a> | {{ post.createdDate }}
                </div>
                <p>{{ post.body }}</p>
            </div>
        </div>
    </div>
</template>
<script>
import Event from '../event.js';

export default {
    data() {
        return {
            posts: [],
            post: {}
        }
    },
    mounted() {
        Event.$on('added_tweet', (post) => {
            this.posts.unshift(post);
        });
    }
}
</script>

Step 11: Display Follow or Unfollow link.

Create a migration file for Followers table.

Type the following command to generate model and migrations.

php artisan make:model Follower -m

Now, write the following schema inside create_followers_table.

// create_users_table

public function up()
{
        Schema::create('followers', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->integer('follower_id')->unsigned();
            $table->nullableTimestamps();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('follower_id')->references('id')->on('users')->onDelete('cascade');
            
        });
}

Migrate the table.

php artisan migrate

Now, we need to set up the relationship with the User model.

// User.php

public function following()
{
   return $this->belongsToMany(User::class, followers, user_id, follower_id);
}

Next step is, we need to put some condition that is following.

  1. The user can not follow himself.
  2. If another user is not followed by him, then he can follow the user.
  3. If the user is followed by another user, then he can unfollow him or her.

We will define each condition with the dedicated function inside User.php file.

I am writing total three functions inside User.php model.

  1. function isNot()
  2. function isFollowing()
  3. function canFollow()
<?php

// User.php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

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

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

    protected $appends = ['profileLink'];

    public function posts()
    {
        return $this->hasMany(Post::class);
    }

    public function getRouteKeyName()
    {
        return 'name';
    }

    public function getProfileLinkAttribute()
    {
        return route('user.show', $this);
    }

    public function following()
    {
        return $this->belongsToMany(User::class, 'followers', 'user_id', 'follower_id');
    }

    public function isNot($user)
    {
        return $this->id !== $user->id;
    }

    public function isFollowing($user)
    {
        return (bool) $this->following->where('id', $user->id)->count();
    }

    public function canFollow($user)
    {
        if(!$this->isNot($user)) {
            return false;
        }
        return !$this->isFollowing($user);
    }

}

Okay, now we have written all the conditions regarding function, we can head over to the user.blade.php file and implement the follow or unfollow link.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <h3>{{ $user->name }}</h3>
            @if(auth()->user()->isNot($user))
                @if(auth()->user()->isFollowing($user))
                    <a href="#" class="btn btn-danger">No Follow</a>
                @else
                    <a href="#" class="btn btn-success">Follow</a>
                @endif
            @endif
        </div>
    </div>
</div>
@endsection

Okay, now if you go to your profile, then you can not see any of the follow or unfollow link.

If you sign in with the different user, then you can be able to see follow or unfollow button.

Step 12: Follow the User.

Define the users/{user}/follow route inside a web.php file.

<?php

// web.php

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');
Route::post('tweet/save', 'PostController@store');

Route::get('users/{user}', 'UserController@show')->name('user.show');

Route::get('users/{user}/follow', 'UserController@follow')->name('user.follow');

Now, we can write the follow() function inside UserController.php file.

// UserController.php

public function follow(Request $request, User $user)
{
    if($request->user()->canFollow($user)) {
        $request->user()->following()->attach($user);
    }
    return redirect()->back();
}

Also, we need to update the user.blade.php file.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <h3>{{ $user->name }}</h3>
            @if(auth()->user()->isNot($user))
                @if(auth()->user()->isFollowing($user))
                    <a href="#" class="btn btn-danger">No Follow</a>
                @else
                    <a href="{{ route('user.follow', $user) }}" class="btn btn-success">Follow</a>
                @endif
            @endif
        </div>
    </div>
</div>
@endsection

Now, when you sign in with another user and type your profile url, you can see that you will be able to follow that user and then after click the follow button, you can see that there is unfollow button.

Also, we can see that the followers table has now one entry.

Laravel Vue Example Tutorial

 

Step 13: Unfollow the User.

We can unfollow the user, which is currently following. So we can write the following function inside User.php file.

// User.php

public function canUnFollow($user)
{
    return $this->isFollowing($user);
}

Also, we need to define the unfollow route inside a web.php file.

// web.php

Route::get('users/{user}/unfollow', 'UserController@unfollow')->name('user.unfollow');

Now, write the unFollow() function inside UserController.php file.

// UserController.php

public function unFollow(Request $request, User $user)
{
   if($request->user()->canUnFollow($user)) {
       $request->user()->following()->detach($user);
    }
       return redirect()->back();
}

Also, we need to update the user.blade.php file.

@if(auth()->user()->isNot($user))
      @if(auth()->user()->isFollowing($user))
           <a href="{{ route('user.unfollow', $user) }}" class="btn btn-danger">No Follow</a>
      @else
           <a href="{{ route('user.follow', $user) }}" class="btn btn-success">Follow</a>
      @endif
@endif

Now, finally, the follow and unfollow functionality is over.

Step 14: Fetch tweets based on the following user.

Okay, till now, we have successfully completed all the task.

Next task is to fetch all tweets, whom you follow. So, when we start following any users, we can see their tweets.

So, we can define the index() function inside PostController.php file.

<?php

// PostController.php

namespace App\Http\Controllers;

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

class PostController extends Controller
{

    public function index(Request $request, Post $post)
    {
        $posts = $post->whereIn('user_id', $request->user()->following()
                        ->pluck('users.id')
                        ->push($request->user()->id))
                        ->with('user')
                        ->orderBy('created_at', 'desc')
                        ->take($request->get('limit', 10))
                        ->get();
          
        return response()->json($posts);
    }

    public function store(Request $request, Post $post)
    {
        $newPost = $request->user()->posts()->create([
            'body' => $request->get('body')
        ]);
   
        return response()->json($post->with('user')->find($newPost->id));
    }
}

So, here, I have fetched all the posts, which is currently signed in user as well as all the user’s that is currently signed in user is following. It may be more than one user.

Basically, what I am trying to say is that Currently signed in user can see his post as well as other people’s post, which he is following at the moment.

Now, all we need to do is display all the posts.

Define the route for this index() function.

// web.php

Route::get('posts', 'PostController@index')->name('posts.index');

Okay, now finally, we need to send a network request using axios library.

We need to define the axios get request inside our TimelineComponent.vue file.

// TimelineComponent.vue

<template>
    <div class="col-md-8 posts">
        <p v-if="!posts.length">No posts</p>
        <div class="media" v-for="post in posts" :key="post.id">
            <img class="mr-3" />
            <div class="media-body">
                <div class="mt-3">
                    <a :href="post.user.profileLink">{{ post.user.name }}</a> | {{ post.createdDate }}
                </div>
                <p>{{ post.body }}</p>
            </div>
        </div>
    </div>
</template>
<script>
import Event from '../event.js';

export default {
    data() {
        return {
            posts: [],
            post: {}
        }
    },
    mounted() {
        axios.get('/posts').then((resp => {
            this.posts = resp.data;
        }));
        Event.$on('added_tweet', (post) => {
            this.posts.unshift(post);
        });
    }
}
</script>

Now, you can be able to see all the post from your following user as well as your posts.

Laravel Vue Twitter Style App

 

Finally, our Laravel and Vue Example | Build a twitter type web application tutorial is over.

In this Laravel and Vue Example, we have covered lots of things and concepts.

I hope it can help you with your real-time projects.

This is not same twitter app, but I am just trying to teach you some of the concepts like Events in Vue.js, Laravel Model relationships and complex queries.

I am putting this Laravel and Vue Example project on Github so you can check it out there. 

Github Code

Steps to use Github

  1. Clone the repo and go into the folder.
  2. Type the following command: composer install
  3. Install npm dependencies: npm install
  4. Start the watch: npm run watch
  5. Create a database and configure inside the .env file.
  6. Migrate the database: php artisan migrate
  7. Register the two users.
  8. Create some tweets using the signed in user.
  9. Logout that user and sign in with the second user.
  10. Go to the first user’s profile and follow it.
  11. Go to the home route and now you can see that followed user’s post.
  12. Now, create the tweets using second user and you can also see that tweets.

The post Laravel and Vue Example | Build a twitter type web application appeared first on AppDividend.

]]>
https://appdividend.com/2018/06/11/laravel-and-vue-example-tutorial/feed/ 4
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/ 6
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
How To Create A Global Event Bus With Vue.js https://appdividend.com/2018/06/03/how-to-create-a-global-event-bus-with-vue-js/ https://appdividend.com/2018/06/03/how-to-create-a-global-event-bus-with-vue-js/#comments Sun, 03 Jun 2018 10:16:26 +0000 http://localhost/wordpress/?p=957 Global EventBus in Vue

How To Create A Global Event Bus With Vue.js is the today’s leading topic. An event bus is the pub/sub pattern. Means one component publishes an event and another component subscribes to that event. So one component Vue component emits an event with some data, and another component subscribes to that event and receives that […]

The post How To Create A Global Event Bus With Vue.js appeared first on AppDividend.

]]>
Global EventBus in Vue

How To Create A Global Event Bus With Vue.js is the today’s leading topic. An event bus is the pub/sub pattern. Means one component publishes an event and another component subscribes to that event. So one component Vue component emits an event with some data, and another component subscribes to that event and receives that data. 

It is the quick way to passing the data from parent to child or child to the parent component. The Universal solution for passing the data between Vue components are Vuex centralized state management library, but for a small scale web application, we can use the Event Bus architecture to pass the between the components.

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

Global Event Bus With Vue.js

For simple web architecture, it is enough to communicate between components using events. The quick solution to this problem is to implement EventBus. EventBus allows us to emit an event from one component and listen for that event in another component.

Now, let us implement EventBus in Vue.js.

Step 1: Install Vue.js.

We will install Vue.js using the Vue CLI.

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

Then create a new project using the following command.

vue create ebus

 

Global Event Bus With Vuejs

Step 2: Architecture of EventBus.

Now, first, we need a mechanism to transfer an event from components. So first let us create that mechanism using Vue.js.

First, go to the project folder, if you are not in there.

cd ebus

Now, open the project folder in your editor or IDE.

code .

Now, inside src directory, create one file called Events.js.

Write the following code inside Event.js file.

// Events.js

import Vue from 'vue';

export const EventBus = new Vue();

That is it, guys. We have created a Vue instance and now that instance we can use as an Event Bus.

Now any component can emit an event with this instance and also other components can listen for that event using this event bus.

Step 3: Create an Event EmitterComponent.

Let us create a component inside src >> components folder.

We name the component as EmitterComponent.vue.

// EmitterComponent.vue

<template>
  <button @click="clickMe()"></button>
</template>

<script>
import { EventBus } from '../Events.js';

export default {
  data() {
    return {
      count: 0
    }
  },

  methods: {
    clickMe() {
      this.count++;
      EventBus.$emit('emittedEvent', this.count);
    }
  }
}
</script>

So, when a user clicks the button, it fires click event, and in that click event, we have called a function.

Here the function name is clickMe(), and that function emits an event using EventBus.

Step 4: Listen for the event.

Create a component inside src >> components folder called ListenComponent.vue.

Write the following code inside ListenComponent.vue file.

// ListenComponent.vue

<template>
<div>
    Count number is: {{ value }}
</div>
</template>

<script>
import { EventBus } from '../Events.js';

export default {

    data() {
        return {
            value: 0
        }
    },
    mounted() {
        EventBus.$on('emittedEvent', data => {
            this.value = data;
        });
    }
}
</script>

So, what I have done is thatListenComponent component is ready to listen to the event emitted from EmitterComponent.

When the event is emitted, ListenComponent listens to that event and get the data and assign that data.

Now, we can easily display that data.

Step 5: Register both the components.

Now, write the following code inside src >> App.vue file.

// App.vue

<template>
  <div id="app">
    <emitter-component></emitter-component>
    <listen-component></listen-component>
  </div>
</template>

<script>
import EmitterComponent from './components/EmitterComponent.vue'
import ListenComponent from './components/ListenComponent.vue'

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

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

Now, save the file and start the server using the following command.

npm run serve

Go to this link: http://localhost:8080/

When you click the button, the count is increment every time.

So, we have passed the data successfully from one vue.js component to another component.

Removing Event Listeners

You can unregister the events using the following function.

EventBus.$off('emittedEvent');

If you want to remove all event listeners, then you need to write the following code.

EventBus.$off();

You do not need to pass any argument at all.

Finally, Create A Global Event Bus With Vue.js is over.

 

The post How To Create A Global Event Bus With Vue.js appeared first on AppDividend.

]]>
https://appdividend.com/2018/06/03/how-to-create-a-global-event-bus-with-vue-js/feed/ 2