vuex2.0+vue2.0 Construction Memo Application Practice _javascript Skills

Source: Internet
Author: User
Tags commit knowledge base

First, introduce Vuex

Vuex is a state management model specifically developed for vue.js applications. It takes the state of all components applied by centralized storage management and ensures that the state changes in a predictable manner with the corresponding rules, and is suitable for large single page applications in construction.

1, what is the state management mode?
Look at a simple example:

<! DOCTYPE html>  

The code identifies:

1, state, driving the application of the data source;
2, view, map to the view of the data countervalue;
3, actions, in response to the user input on the view caused by the changes in the state.

Express their relationship with a simple schematic diagram:

As we know, medium and large applications typically encounter multiple components sharing the same state :

1. Multiple views depend on the same state
2. Behaviors from different views need to change the same state

It is therefore necessary to extract the shared state of the component to be managed in a global single case pattern , and to define and isolate the various concepts in state management and enforce adherence to certain rules.

This is the basic idea behind Vuex, drawing on the Flux, Redux, and the ELM architecture. Unlike other patterns, Vuex is a state management library designed specifically for Vue.js to use Vue.js's fine-grained data response mechanism for efficient state updating.

2, the core concept of Vuex

1, state: A single status tree, with an object containing all the application-level state, as a "unique data source (Ssot)" exists, each application will only contain a store instance.
2), Getters:vuex allows us to define "getters" in the store (which can be considered the calculation property of the store).
3, mutations in MUTATIONS:VUEX are very similar to events: Each mutation has a string event type (type) and a callback function (handler). The callback function is where we actually make the state change, and it accepts the states as the first argument.
4, Actions: Similar to mutation, the difference is: ①action submitted is mutation, rather than directly change the state; ②action can contain arbitrary asynchronous operations.
5), Modules: In order to solve a single state tree cause the application of all the state to focus on a store object's bloated problem, vuex the store into modules (module). Each module has its own state, mutation, action, getters, or even a nested module-a similar split from top to bottom.
Then we start building the memo application, and in the following build process, we can deepen our understanding of the above concepts.

Second, environmental installation

1. Install VUE-CLI

2. Initialization application

Vue Init webpack vue-notes-demo
CD vue-notes-demo
npm Install//Installation Dependency pack
npm Run dev/start service


The results are:

The directory structure is:

Third, Function module

Let's see what we're going to do with the demo:

The main functional modules are:

New Plan, add a plan, the edit area shows empty plan content.

removes the plan, and after deleting a plan, the plan is less than the plan list.

The total length of all plans, add up all the planned time.

Iv. Project Component Division

In the original directory structure adjustment, the final directory structure is:

The following details are described below:

1. Component parts
1). Home component: Home.vue

<template>
 <div class= "Jumbotron" >
  
 

2. Calculation plan Total time length component: Sidebar.vue

<template>
 <div class= "Panel Panel-default" >
 <div class= "panel-heading" >
 

3). Plan List component: Timeentries.vue

<template> <div> <router-link v-if= "$route. Path!== '/time-entries/log-time '" to= "/time-entries/log-t
 IME "class=" btn Create-plan > Create </router-link> <div v-if= "$route. Path = = '/time-entries/log-time '" >  

4). New Schedule Component: Logtime.vue

<template> <div class= "Form-horizontal" > <div class= "Form-group" > <div class= "col-sm-6" > < label> Start date:</label> <input type= "date" class= "Form-control" v-model= "date" placeholder= "date" ;/div> <div class= "col-sm-6" > <label> total time  :</label> <input type= "number" class= "Form-con Trol "v-model=" TotalTime "placeholder=" Hours "/> </div> </div> <div class=" Form-group "> <di V class= "col-sm-12" > <label> remarks   :</label> <input type= "text" class= "Form-control" V-mode L= "comment" placeholder= "comment"/> </div> </div> <button class= "btn btn-primary" @click = "Save ()" &
 gt; save </button> <router-link to= "/time-entries" class= "btn Btn-danger" > Cancel </router-link>  

2, the Vuex used to store data is divided into:
1). Initialization of Vuex.Store:index.js

Import Vue from ' Vue '
import Vuex from ' Vuex '
import mutations to './mutations '
import actions from './actio NS '

vue.use (VUEX);

Const STATE = {
 totaltime:0,
 list: []
};

Export default New Vuex.store ({State
 ,
 mutations,
 actions
})

State : a singleton tree, with a state object that contains all the application-level states, only one new Store instance Vuex.store in the code.

2. Responsible for triggering events and incoming parameters: Actions.js

Import * as types from './mutation-types '

export default {
 Addtotaltime ({commit}, time) {
 commit (types. Add_total_time, Time)
 },
 Dectotaltime ({commit}, time) {
 commit (types). Dec_total_time, Time)
 },
 Saveplan ({commits}, plan) {
 commit (types). Save_plan, plan);
 },
 Deleteplan ({commit}, plan) {
 commit (types). Delete_plan, Plan)
 }}
;


In practice, we often use ES2015 parameter deconstruction to simplify the code (especially when we need to invoke a commit many times):

Actions: {
 increment ({commit}) {
 commit (' increment ')
 }
}

3. Registration of various data changes methods: Mutations.js

Import * as types from './mutation-types '

export default {
 //Increase total time
 [types. Add_total_time] {
 state.totaltime = State.totaltime +
 Time},
 //reduce total times
 [types. Dec_total_time] (state, time) {
 state.totaltime = State.totaltime-time
 },
 //new plan
 [types. Save_plan] (state, plan) {
 //Set default value, future we can do login direct read nickname and avatar
 const AVATAR = ' https://pic.cnblogs.com/avatar/ 504457/20161108225210.png ';

 State.list.push (
 object.assign ({name: ' Eraser ', Avatar:avatar}, plan)
 },
 //delete a schedule
 [ Types. Delete_plan] (state, IDX) {
 state.list.splice (idx, 1);
 }
};

Using constants instead of mutation event types is a common pattern in various Flux implementations. This allows tools such as linter to work, while keeping these constants in a separate file allows your code collaborators to mutation the entire app:

Mutation-types.js 
Export Const Some_mutation = ' some_mutation '

mutations: {
 //we can use ES2015 The style evaluates property naming function to use a constant as the function name
 [some_mutation] (state) {
 //mutate State
 }
 }

4. Log all event names: Mutation-types.js

Increase total time or reduce total time
export const Add_total_time = ' add_total_time ';
Export Const Dec_total_time = ' dec_total_time ';

Add and remove a plan
export const Save_plan = ' Save_plan ';
Export Const Delete_plan = ' Delete_plan ';

With the above constants instead of the mutation event type

3. Initialization section
The import file renders the template index.html relatively simple:

<! DOCTYPE html>
 
 

Code for entry file Main.js:

Import Vue from ' Vue ';
Import App from './app ';
Import home from './components/home ';
Import timeentries from './components/timeentries.vue '

import vuerouter from ' Vue-router ';
Import Vueresource from ' Vue-resource ';
Import store from './vuex/index ';


Routing module and HTTP module
vue.use (vueresource);
Vue.use (vuerouter);

 Const ROUTES = [
 {path: '/home ', component:home},
 {
 path: '/time-entries ',
 component:timeentries ,
 Children: [{
 path: ' Log-time ',
 //lazy load
 component:resolve => require (['./components/ Logtime.vue '],resolve),
 }]
 },
 {path: ' * ', component:home}
]
const ROUTER = new Vuerouter ({ C24/>routes//short for Routes:routes
});
Router.start (App, ' #app ');
Const APP = new Vue ({
 router,
 store,
 ...) APP,
}). $mount (' #app ');

In code ... App equivalent to Render:h => H (APP)
Initialize Component App.vue as:

<!--//Src/app.vue--> <template> <div id= "wrapper" > <nav class= "NavBar Navbar-default" > < div class= "Container" > <a class= "Navbar-brand" href= "#" > <i class= "Glyphicon glyphicon-time" ></i > Memo </a> <ul class= "Nav navbar-nav" > <li><router-link to= "/home" > Home page </router-link>& lt;/li> <li><router-link to= "/time-entries" > Program list </router-link></li> </ul> </ div> </nav> <div class= "container" > <div class= "col-sm-9" > <router-view></router-view&
 Gt </div> <div class= "col-sm-3" > <sidebar></sidebar> </div> </div> </div> <  /template> <script> import Sidebar from './components/sidebar.vue ' export default {components: {' Sidebar ': Sidebar},} </script> <style>. router-link-active {color:red;} body {margin:0px; navbar {height
 : 60px;
 line-height:60px; backgRound: #333;
 }. NavBar a {Text-decoration:none}. navbar-brand {display:inline-block;
 margin-right:20px;
 width:100px;
 Text-align:center;
 font-size:28px;
 text-shadow:0px 0px 0px #000;
 Color: #fff;
padding-left:30px;
 }. avatar {height:75px;
 margin:0 Auto;
 margin-top:10px; /* margin-bottom:10px;
 */}. text-center {margin-top:0px; /* MARGIN-BOTTOM:25PX;
 */} time-block {/* padding:10px; * * MARGIN-TOP:25PX;
 }. comment-section {//////////////} col-sm-9 {float:right; /* margin-right:60px;
 * * width:700px;
 min-height:200px;
 Background: #ffcccc;
 padding:60px;
 }. Create-plan {font-size:26px;
 Color: #fff;
 Text-decoration:none;
 Display:inline-block;
 width:100px;
 Text-align:center;
 height:40px;
 line-height:40px;
 Background: #99cc99;
 }. col-sm-6 {margin-top:10px;
 margin-bottom:10px;
 }. col-sm-12 {margin-bottom:10px;
 }. btn-primary {width:80px; Text-align:center;
 height:30px;
 line-height:30px;
 Background: #99cc99;
 border-radius:4px;
 Border:none;
 Color: #fff;
 Float:left;
 margin-right:10px;
 font-size:14px;
 }. btn-danger {display:inline-block;
 font-size:14px;
 width:80px;
 Text-align:center;
 height:30px;
 line-height:30px;
 background:red;
 border-radius:4px;
 Text-decoration:none;
 Color: #fff;
 margin-bottom:6px;
 } row {padding-bottom:20px;
 border-bottom:1px solid #333;
 position:relative;
 Background: #f5f5f5;
 padding:10px; /* padding-bottom:0px;
 */}. Delete-button {position:absolute;
 top:10px;
 right:10px;
 }. panel-default {position:absolute;
 top:140px;
 right:60px;
 } </style>

So far, the end of practice, some of the original rational things I still need to understand ^_^

Source code: "Vuex2.0 Practice"

Reference:

vue2.0 to build a single page application best combat

vuex2.0 Document

About Vue.js 2.0 Vuex 2.0 you need to update the Knowledge base

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.