Vue.js Application Development Notes

Source: Internet
Author: User

See vue.js have a few days, before also fragmented, but have not hand to write demo, this few days backstage matter relatively little, has been discussing various needs (in fact, the company on demand or more attention and rigorous, a project needs to discuss almost a week, this to put before, God ... , so I think of the simple vue, such as the following is only a personal understanding, not to the place also looked at the garden friends, involved in the things have Vue, Vue-router, Vuex, Axios and Nodejs some backstage things, nonsense not to say directly to serve it.

First, Vue.js

1, the project construction use VUE-CLI Scaffolding, first must install Vue, VUE-CLI:cnpm i vue vue-cli-g, after the global installation we can use the VUE-CLI scaffold to build the project structure, Specific as follows:

Vue Init Webpac k frontend , as follows:

Here we select the Environment section "Environment + build environment", so that you can use Webpack directly after the post-compilation deployment, it is very convenient, and then continue:

Generally each team has its own code specifications, this time to open Eslint, configure their own team code is particularly important, below the Vscode editor how to configure Eslint, on the basis of the previous project we configured under Eslint, First, Vscode installs the Eslint plugin:

Then configure the specific Eslint rule in the User settings bar:

Open the Vscode file, preferences, user settings, and in the right-hand side of the editor, enter the Eslint rules that we have defined:

{    "editor.fontsize": +,    "Editor.tabsize": 2,    "Editor.formatonsave": false,    "Files.associations": {        "*.vue": "Vue"    },    "Eslint.validate": [        "JavaScript",        "Javascriptreact",        "html",        " Vue ",        {            " language ":" HTML ",            " AutoFix ": True        }    ],    " Emmet.syntaxprofiles ": {        " Vue-html ":" HTML ",        " vue ": [            " CSS ",            " html ",            " less "        ]    },    " editor.fontfamily ":" Source Code Pro, ' Courier New ', monospace ",    " Files.autosave ":" Off ",    " Workbench.icontheme ":" Vscode-icons "}

Here we set the font size to 17,tab indentation of 2 spaces, eslint of the check for JS, HTML, vue, set Vscode icon for Vscode-icons, other rules can refer to Eslint official instructions.

2. Project Structure

The project structure previously generated by VUE-CLI is as follows:

Mainly src folder, we have some expansion of it, where the API folder is used to store the front-end various request API modules, the Components folder is as follows:

Used to store a variety of page components, where base is a common component, such as some header, footer, paging components and so on, home-based interface, the page through the router road to integrate other components, login as login components. The mock folder is used for mock.js configuration so that the front-end can be developed independently of the backend interface and is more efficient using virtual data without relying on the backend. The router folder is used to configure various front-end routes under Vue-router, Vuex folders are primarily used to configure VUEX state management-Related:

Where the Modules folder is used to store each VUEX module, sub-modular configuration, there is a good thing is that when the project is relatively large to facilitate data viewing and management, Mutation.types.js is used to store a variety of VUEX mutation type constants, about Vuex continue to introduce.

3, about vue.js some knowledge points

1), Component concept

Components This is a good explanation, the simple understanding is one by the Vue own way registered pages (can be public pages can also be a single page), component development through the template package of a series of parts of the function page can be called components, such as our App.vue:

Of course, each component has its own scope, and the individual data and related operations under the component are written in the script tag under the current component, as follows:

You can see the data structure as above for the App.vue component, where the current Vue instance is exported through ES6 's export default, which contains a lot of things, such as data (data is a function, By return a data object to represent which data instances are present for the current component, components (which can be used by other components to declare the subassembly imported by the current component), computed (computed properties, similar to data, Essentially returns a data object), watch (listening, mostly listening to changes in the data object, changing the corresponding function), mounted (the hook function is called when the component is initialized), methods (the most used, the private method under the current component, Can be called through This.methodname), events (event, the current component of the event function), there are many, specifically can refer to the official website.

Of course, each component has its own style, which is defined using the following:

The scoped here indicates that the style below is only valid for the current component, otherwise the global is valid, through @import we can import foreign style files (here public resources we generally defined in SRC Assets folder, do not write under the static folder, Because the assets will be packaged automatically, in order to unify or put under assets)

2), data exchange between components

The first is data exchange between parent and child components:

The parent component is like our App.vue component, the subcomponents are the components we import into, Vue.js provides us with a convenient way to communicate across components, for parent-child components that is: subcomponents dispatch events to the parent component, The parent component broadcast the event to all of the following subcomponents , and the default event is transmitted as a bubbling transport. What do you mean, That means that in App.vue we can distribute events directly through the dispatch method, provided that the parent component needs to be configured to change events in methods or events (only if the event is configured to be received, recommended in events), and, of course, some data can be delivered when distributed, and the parent component is also a The broadcast broadcast event to the child component. The second is that we can do this through the props property, where the subcomponents specify which attributes need to be prop in the script tag, and the parent component writes the prop directly where the subassembly is called (Dynamic prop if the V-bind:prop is added). Then the data is passed directly from the parent component to the child component. Thirdly, we can communicate the event through the global $emit, which can refer to the official website document.

The second is how any non-relational component communicates:

This time need to use intermediate components for data transmission, the equivalent of building a central data bus, such as a component needs to communicate with the C component, then we can define an empty component is B, then in the a component to import B components, while distributing events to the B component, while importing the B component in the C component, and receive the event here. Of course, if you know Vuex, using Vuex can easily solve the communication problem between any component, which is said later.

3), vue.js instance Properties

One is $.parent and $.children, both of which get the parent instance of the current component, one that gets all the subcomponents of the current component, and the methods, data resources, and so on that make it easy to access the instance after it gets to the component. $.refs is where the parent component calls the subassembly, in order to differentiate the subcomponents, you can specify a different ref attribute for the component, and then you get the subcomponent instance through this. $refs. xxx, and then you can perform various instance operations.

4. Operation effect

Just said so much, our project is almost set up, through the command line:npm run Dev, and then directly in the browser to see the effect:

The default startup is 8080 ports, accessed under:

Here, everything is OK, simple vue.js Scaffolding project is completed.

Second, Vue-router

See router, as the name implies "route" meaning, Vue-router give spa app front-end routing right, so that the custom page jump instead of requesting the server, the main record is as follows:

1, Configuration Vue-router

In front of the scaffold project we have generated a scaffold project with Vue-router, the following is mainly to make some changes to the description:

Import vue from ' Vue ' import Router from ' vue-router '//import store from '. /vuex '//import App from '. /app.vue '//import _ from ' Lodash ' Vue.use (Router) Export const Router = new Router ({  mode: ' History ',  routes: [
   //component Lazy Load, this prevents the component too much on the first screen open slow problem    {path: '/user ', component:resolve = require ([' ... /components/user/user.vue '], resolve)},    {path: ' * ', component:null}  ]}) Router.beforeeach (to, from, next) =& Gt {//To and from is  Route Object,next () must is called to resolve the hook  //if (!store.getters.logined) {  / /} else {  //   Next ()  //}  Next ()})

Router must use Vue.use for global registration to use, the mode parameter is used to configure the router pattern, the default is the hash mode with "#", of course, the configuration of history uses H5 history mode, the route is more like a normal URL. Routes is used to configure various specific routing information, here routes is an array of objects, each object is a routing object, including path (route path, support regular match), component (the route corresponding to the component instance), note that In general, we do lazy loading of the routing components to speed up the first screen rendering speed.

2. Configure the use in the component

Router-view is used for the display of the routing view, the first step is to configure the route corresponding to each route, then once a page uses Router-view for the view display, it happens that the route matches the above path, Then the corresponding component of path will be shown in the location of Router-view, which is equivalent to the filling of the routing component. Of course a page or component can be configured with multiple Router-view, then the corresponding need to introduce multiple component instances.

Router-link is a routing jump tag that can be understood as a tag in our HTML, the Router-link tag contains property to, and can also be routed to the configuration.

About routing methods:

Router.push (), Router.replace (): Route jump

Router.back (): Route fallback

Router.forward (): Forward jump

Other reference official website shows that the application of more is the Beforeeach method, all routing calls before the implementation of the method, here we can generally do some permissions to judge, login judgment and other operations:

Third, Vuex state management

Vuex is mainly used for global state management, it can be understood as the global data management, Vuex mainly consists of several parts: action, mutation, getters, states, the general use process is: The component can directly call the above four parts, such as Call action , you can use: this. $store. Actionname,mutation is the same, but the action supports asynchronous invocation, and the operation under mutation is completely synchronous , that is, The action can invoke various API calls (the API method is generally asynchronous and returns the Promise object). Component Access Getters:this. $store. Getters.gettersname, the component calls State:this. $store. Modulename.statename (This is accessed in a modular configuration Vuex). The action generally commits the event to mutation, then the data in the state is manipulated in mutation, and finally through the getters exposes the data in the state to the component, and if it does not involve an asynchronous operation, You can dispatch the corresponding mutation directly in the component and skip the action to manipulate the state directly.

1, Configuration Vuex

The first is the user module content under module:

Import * as types from '. /mutation.types ' Import * as HTTP from '. /.. /api/http '//import _ from ' lodash ' const state = {userinfo:JSON.stringify (Localstorage.getitem (' userinfo ') | | {})}const actions = {Setuserinfo ({commit}, UserInfo) {localstorage.setitem (' userinfo ', userinfo) commit (types.  Set_userinfo, USERINFO)}, login ({Dispatch, Commit, getters}, Plyload) {return http.get ('/user/caiya ', {})}}const Mutations = {[Types. Set_userinfo] (state, USERINFO) {state.userinfo = USERINFO}, [Types.    LOGOUT] (state) {Localstorage.setitem (' userinfo ', ') State.userinfo = "}}const getters = {logined (state) { return state.userinfo!== ' && state.userinfo!== ' {} '}, UserInfo (state) {if (State.userinfo!== ' &am    p;& state.userinfo!== ' {} ' && typeof state.userinfo = = = ' String ') {return json.parse (state.userinfo) } else if (typeof state.userinfo = = = ' object ') {return state.userinfo} return null}}export deFault {state, actions, mutations, getters} 

Each module has a corresponding four components, defined as above, and then configured in the Index.js module:

Import vue from ' Vue ' import Vuex from ' Vuex ' import user from './modules/user ' Vue.use (VUEX) export default new Vuex.store ({ C1/>modules: {    user  }})

Finally, the store is configured to the global Vue instance:

2. Actions

The actions receive a key-value pair function, which is the first parameter of the Vuex context object, which includes the dispatch, commit, getters object functions, which can be directly obtained by means of the ES6 structure:

It can then be done directly, or you can do this in the payload data commit to mutation.

3, mutation

Mutation is generally used to modify the data in the state, where the first parameter is the state object, the parameters are variable, are the arguments passed by the action or the page passed directly through the dispatch parameters.

4, getters

You can see that getters is actually used to filter the data in the state, and the first parameter of each getters function is the state object under the current module. After defining the getters, you can obtain the filtered data in the state by directly acquiring the getters in the component:

5, finally see the state to operate

In fact, the state is a JSON object used to hold arbitrary states:

6. Component Auxiliary functions

What do helper functions do, such as actions, mutation, getters, and state that we've defined before, and what do they want to do with the components? You must use this . $store. getters.xxx to get getters xxx, to invoke action you must use this.$ Store.actionname to invoke, mutation similarly, get state to use this.$ Store.state.moduleName.stateName gets the state data for the StateName under the specified modulename, so the call is cumbersome, so the helper function appears.

For example, our Login.vue component needs to invoke the login method in actions as follows:

In the same way we can call mutation like this directly:

Let's look at a getters:

Iv. Axios

Axios is an HTTP request package, similar to Vue-resource (the package has been stopped maintenance), Vue official website recommends using Axios for HTTP calls, because Axios compressed after the volume is smaller, support restful method calls, about the use of Axios see the following code, There are detailed descriptions:

Import Axios from ' axios ' Axios.defaults.baseURL = ' https://cnodejs.org/api/v1 '//axios.defaults.headers.common[' Authorization '] = auth_tokenaxios.defaults.headers.post[' content-type '] = ' application/x-www-form-urlencoded ' const Access_token = ' accesstoken=ed20aac8-9fd8-45bf-8112-62fd2425b4a5 '//Add request Interceptor axios.interceptors.request.use (config = > {//What to do before sending the request Config.url = ' ${config.url}?${access_token} ' return config}, error = {//What to do with the request error return Promise.reject (Error)})//Add Response interceptor axios.interceptors.response.use (response = =//Do something about the response data return response}, error = = {//do something to respond to errors return Promise.reject (Error)}) export function fetch (URL, params) {return new Promise (Resolve, R Eject) = = {Axios.post (URL, params). Then (res = = {Resolve (res)}). catch (Err = {reject (err)} )})}export function get (URL, params) {return new Promise ((resolve, reject) = {Axios.get (URL, {params:p    Arams}). Then (res = {Resolve (res)}). catch (Err = {reject (ERR)})})} 

This http.js file is exported and can be called directly in action without the global Vue configuration, which is very convenient. the Axios.interceptors.request method is mainly used to add interceptors to all requests, where you can perform various request permission checks, method rewriting, etc. Axios.interceptors.response mainly on the response to intercept processing, such as our server return status code 403, indicating no access information, then this can be directly related to the error message display, or directly to the login or other pages.

How far simple application

Spare time to do a simple login and backstage management system (PS: Just start), simple effect as follows, GitHub address: https://github.com/caiya/frontend:

Six, finally want to say a few more words

1, any technology, want to learn to do more hands to do, practice out of the truth Ah, light see do not withstand the test of actual combat

2, more than write blog is good hahaha, not only practice writing, edify sentiment is also some, not to mention those dauntless spirit of sharing

Vue.js Application Development Notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.