Laravel, Vuejs, Router View

Tram Ho

Preamble

Hello everyone, continue with the vuejs series today, I would like to introduce you to the Vue router.
Currently, one-page SPA (Single Page Application) is becoming more and more popular. As a web page only on one page, ie instead of loading the whole website to get all the content that has been loaded before, SPA will task to load only the parts that need to be changed. No need to load to reduce server load and make our site faster, more professional. Specially made for a better user experience.

 

What is Vue Router?

Vue Router is the official router for Vue.js. It integrates deeply with the Vue.js core to make it easy to build Single Page Applications with Vue.js.

User manual

In this post, I will try to demo with laravel 5.8. First you need to install laravel:

Next I install the router vue

Because laravel has already integrated vuejs into the project, we don’t need to do much. Just embed the script file we built into.

We will navigate the default laravel into a single file view as follows:

Here at my web.php file, the web.php router navigates to a single view file. In this view file will embed the js file we have built and from there this js file will navigate to the required views.

at file view home.blade.php

As you can see, I only embed the app.js file built from vuejs components and other necessary js files. Laravel is configured to build these files in webpack.mix.js file using the Laravel mix. You can see more about Laravel mix in this article of mine. And after the build is complete we have the file at public/app.js and from there we just need to import into our home view file. To build you execute the command

Next I will create 3 components as follows: I will create 3 components in resource / js / components directory

The content of these 3 files will be as follows:

In the User file as follows:

Next we create a routes.js file in the js / directory with the following content:

Here:

path : is the path displayed in the address bar,
component : is the component that will be rendered into the layout
name : used to identify the route, so we can use it more conveniently.
There are also many other attributes, you can refer to the document link https://router.vuejs.org/guide/essentials/named-routes.html

Next in the file js / app.js will modify the following to import vue-router and declare use:

The above has the following:

There is a mode: ‘history’ that works as follows: Without this mode, by default when entering the path, we will have a # in the browser.

For example: localhost / # / user Ok, see if npm has finished building, then go outside to load your browser to see the home view and load the contents of the App.vue component:

And the final step in the App.vue file is amended as follows:

We need to pay attention to the following 2 places:

Next is:

Go outside to test again: Very simple, right. ?

Share the news now

Source : Viblo