Before writing:
After the basic functions of cnode are initially implemented in the first version, the basic information of users returned after successful logon is stored locally, which is used for subsequent reply functions, view the data of basic user information required for operations such as information. But in general, I feel that the local storage solution is not ideal (my personal thoughts), so I want to introduce vuex to store user information and some cross-component statuses and data.
What is vuex? Why?
A brief introduction to what vuex I understand is, because we know that the sub-parent of vue components can implement one-way and two-way data transmission through props, however, we may often encounter a business scenario where the status of a component changes and needs to be responded to by another component that is not related to it. At this time, if we do not have a global variable, we can't do it, in general, vuex is a global state management. (I think so)
Read the document
For the basic usage of vuex, see Chinese API
Use vuex in the project
Now, you can directly use this function to save user information that has been successfully logged on to vuex. This function is based on the document you have read and have a preliminary understanding of vuex, know the state, mutation? Some basic concepts. Since the examples in the API documentation are just a simple demo, I wrote this function to better suit the actual scenario in a project. (These basic concepts will not be introduced here, because the API must be more detailed than me)
1. Initialization
Create a file store. js code as follows. State defines the parameter variables of the desired state. mutation (state change) is used to change the state. Note that the state in vuex cannot be directly changed. mutation must be used to distribute events. The first parameter of the mutation method must be state, and the parameter can be selected later. The two parameters are defined below in this example.
"Use strict ";
Import Vue from 'Vue'
Import Vuex from 'vuex ';
Vue. use (Vuex );
Const state = {
// When the page is opened, the default logon status is no.
IsLogin: false,
// Save the logon information
UserInfo :{
'Loginname ':'',
'Avatar ':'',
'Id ':'',
'Accesstoken ':''
}
}
Const mutations = {
// Set logon
ISLOGIN (state ){
State. isLogin = true;
},
// Set logon user information
SETUSERINFO (state, name, avatar, id, accesstoken ){
State. userInfo. loginname = name;
Console. log (state. userInfo. loginname );
State. userInfo. avatar = avatar;
State. userInfo. id = id;
State. userInfo. accesstoken = accesstoken;
}
}
Export default new Vuex. Store ({
State,
Mutations
})
2. Set the state.
Create an action. js code as follows to distribute mutation events. Some may wonder why we need to write this file to distribute mutation events. It should be because our mutation must be executed synchronously. If we call back in mutation, it is impossible to determine when the callback function can be executed. Asynchronous operations can be performed for event distribution in actions.
/**
* Change the user logon status to logged on
**/
Export const isLogin = ({dispatch}) => {
Dispatch ('islogin ');
}
/**
* Set user logon information
* Parameter name user name avatar user profile id User id accesstoken user logon id
**/
Export const setUserInfo = ({dispatch}, name, avatar, id, accesstoken) => {
Dispatch ('setuserinfo', name, avatar, id, accesstoken );
}
3. Get the state
Create a getters. js code as follows. The user obtains the status in the state.
// Obtain the user's logon status
Export const getLoginState = (state) => {
Return state. isLogin;
}
// Obtain login user information
Export const getUserInfo = (state) => {
Return state. userInfo;
}
4. Call vuex in the component
Note that the difference between calling vuex in the sub-parent component is that the parent component must define store, and the sub-component is random.
Import store from '../vuex/store ';
Import nvHeader from '../components/header. vue ';
Import {isLogin, setUserInfo} from '../vuex/actions ';
Export default {
Data: function (){
Return {
StrToken :''
}
},
Methods :{
Login: function (){
Let rqdata = {
'Accesskeyen': this. strToken
}
$. Post ('https: // cnodejs.org/api/v1/accesstoken', rqdata, (data) => {
If (data ){
// Log on successfully and change the isLogin status to true.
This. userLogin ();
Console. log (this. userLoginState );
This. setUserInfo (data. loginname, data. avatar_url, data. id, this. strToken)
Window. history. back ();
} Else {
// Failed
}
})
}
},
Components :{
'Nv-header': nvHeader
},
Store: store,
Vuex :{
Actions :{
UserLogin: isLogin,
SetUserInfo: setUserInfo
}
}
}
We are in login. the vue component calls the sub-component header. the vue component is in the header. the vue component calls menu again. the vue component, and the menu component contains a piece of user information that we log on to display the basic information of the currently logged on user. This requires getting the status from the store, however, the status of the store is updated in the event of successful login. vue should automatically respond to display user information
<Template>
<Div class = "meun": class = "{'showmeun ': showm}">
<Div class = "user_info" v-if = "userLoginState">
<Div class = "avatar">
</Div>
<Div class = "name">
<P v-text = "user_name"> </p>
</Div>
</Div>
<Ul>
<Li v-link = "{name: 'Home'}"> homepage </li>
<Li v-link = "{name: 'search'}"> search </li>
<Li v-link = "{name: 'login'}" v-if = "! UserLoginState "> logon </li>
<Li v-if = "userLoginState"> Unread Message </li>
<Li v-if = "userLoginState"> settings </li>
<Li v-link = "{name: 'about'}"> about </li>
</Ul>
</Div>
</Template>
<Script>
Import store from '../vuex/store ';
Import {getLoginState, getUserInfo} from '../vuex/getters ';
Export default {
Props: ['shop'],
Data: function (){
Return {
User_name: this. getUserInfo. loginname | '',
User_avatar: this. getUserInfo. avatar |''
}
},
Vuex :{
Getters :{
UserLoginState: getLoginState,
GetUserInfo: getUserInfo
}
}
}
</Script>
Conclusion:
OK, this login shows the basic functions of user information. Of course, there are still many places where vuex can be used. For example, vuex is also used in the pop-up components of this project to display the corresponding prompt text according to the specific situation. The self-reconstructed Cnode project is gradually being improved. If you think this article has some benefits for you, you can use star to support it. Thank you!
Github source code
Online demo access address
Tip: The online demo provides better access performance when switching the browser to the mobile terminal mode.