In a normal login progress, a solution is:
- Check login status, when user enters a page or when the router changes ( the value stored in cookie or local storage)
- If we find login status, then we can get the user information.
- Otherwise, redirect the user to login page
- In login page, validate user input.
- Send login request
- If not success, the return a error response to user.
- If success, get information and save the login status
- When a user logout, delete login information
Now, install the vue-cli
first by command
1 | install vue-cli |
Register router
Create router
In the src/router/index.js
file, register two routers, the first one is /login
and the other one is /user
. And import two compnents that will be created later.
1 | import Vue from 'vue' |
Check login status
We need to check the login status when: 1. User opening the application, 2. router is changing.
So create a checkLoing
method in /src/main.js
first
1 | // The Vue build version to load with the `import` command |
And then we add this method in the created
hook so that we could check the login status at the start stage.
1 | // The Vue build version to load with the `import` command |
Ceate components
Now create three components under src/components
Loading component
Loading.vue
is used to show the loading status
1 | <template> |
Login component
Login.vue
is used to show the login form and process the login request
1 | <template> |
User component
User.vue
is used to display user information
1 | <template> |
Use Vuex
Actually, above code doesn’t work. This is because the applicaiton hasn’t used the Vuex
How to add vuex, just run the following command in the termainal under the project root folder
1 | npm install vuex --save |
After that, in the src/main.js
file, improt vuex
1 | import Vuex from 'vuex' |
Then, use Vue.use()
to install vuex
1 | Vue.use(Vuex); |
Finally, create a state
1 | const store = Vuex.Store({ |
And modify the checkLogin method
1 | checkLogin(){ |
So the whole main.js
looks like this
1 | // The Vue build version to load with the `import` command |