Explore Vuex 2.0 and build a Notepad app with Vuejs 2.0 + VUEX 2.0

Source: Internet
Author: User
Tags button type hasownproperty

Objective

First of all, this is not a tutorial paste, and Notepad application is an early case of online, for learning Vuex very helpful. My goal was to explore Vuex 2.0 and then rewrite the app with Vue 2.0 + Vuex 2.0, the biggest of which was the problem with using VUE-CLI to build the app. Through these issues in-depth exploration vue as well vuex .

My Learning about frames has been intermittent, and the first contact is react that there are some preconceived notions, like a react little bit more, especially at the construction level of the application. The reason is intermittent, because of their own JS foundation is weak, just start learning, just than gourd painting scoop, although can make something, but some of the concepts are still foggy, unintelligible, unable to deeply understand the framework. So I temporarily abandoned the framework of learning, began to learn the JS Foundation. The learning framework and understanding of the framework are fast after the facts have proven to be grounded. The process of learning WebGL and three.js is similar. Without the basis of WEBGL, learning Three.js will only stay in the initial stage.

I have participated in many interviews in the past six months, almost without exception will be asked about the use of the framework, but many of them belong to the drift, using the framework is more blind. Even feel the use of frames is extremely tall on the thing. Although I have studied the framework, but after all, there is no deep study and not to take the project, so just a few words to say two, most of the knowledge is ignorant. However, in the face of the interviewer's disdain and use it as an indicator of the selection, thought such an interviewer is too superficial. Of course, many companies interview is based on the basis. The framework belongs to the state of exploration and mutual learning. I emphasize in this article that learning ability and problem-solving ability are more important.

Let's go

At the same, for this notebook case, you can directly Baidu search Vue notes, this is an English course, we see are translated. At the beginning of the Vue data scarcity, such an article is very valuable. Demo point here. Plainly, todoMVC a variant of the case. Originally thought this example is very good, wants to follow the study, the result one half year passes. These days I finally took the time to knock the example over. Learning lies in extrapolate. If you follow the online tutorial to do, then the NPM package is installed by default is the latest version, the operation will be error. So how do you write it with Vuex 2?

The following is the source file directory for Notes-vuex-app:

Before using Vue 2 to rewrite this app, I was wondering if I could not change the file directory structure and configuration location? is to rewrite it in a more blunt way, or simply to modify the syntax. The facts are feasible, otherwise I wouldn't have written this article. However, there are a lot of problems to be faced, but it is a deep understanding of Vue and Vuex. The biggest problem is the construction of Webpack, if the use of Webpack 2.0+, pits more. I am a rookie, so finally chose the vue-cli provided by the two Webpack template, respectively, webpack-simple and webpack , I first use webpack-simple , it and the original app structure basically coincide.

After you have used VUE-CLI to generate the base directory, install VUEX2.

Main.js

The original example main.js is shown below, but the operation is wrong, mostly the root instance rendering of Vue 2 changes slightly

Import Vuefrom ' Vue './vuex/store'./components/app.vue 'new  vue ({  //  injected into all subcomponents  el: ' Body ', components  : {App}}

After correction:

Import vue from ' Vue'./vuex/store'./components/app.vue 'new  vue ({     //  inject store to all children    el: ' #app ',    ' <App/> ', Components    : {App}})

Or

Import Vuefrom ' Vue './vuex/store'./components/app.vue 'new  vue ({    //  Inject store    to all children el: ' #app ',    + = h (APP)})
Changes in Vuex 2

The main problem with this application rewriting is the change in Vuex 2, which really makes people feel messy, and I scratching the dozens countless times. However, some clues can be seen through the official examples.

First of action.js all, just note that all the dispatch changes are made commit .

Export Const Addnote = ({commit}) + {commit  (' add_note '= ({commit}, e) + = {  commi T (' edit_note '= ({commit}) = = {commit  (' delete_note' = ({commit}, NOTE) =>< c9> {commit  (' set_active_note '= ({commit}) = = {commit  (' toggle_favorite ') )}

store.jsThe changes are small, but there are several places to note:

Import vue from ' Vue 'Import Vuex from' Vuex 'Import* As actions from './actions 'Vue.use (VUEX) const State={notes: [], Activenote: {}}const mutations={add_note (state) {Const Newnote={text:' New Note ', Favorite:false} state.notes.push (newnote) state.activenote=Newnote}, Edit_note (state, text) {State.activeNote.text=text}, Delete_note (state) {State.notes.splice (State.notes.indexOf (state.activenote),1) State.activenote= State.notes[0] | |{}}, Toggle_favorite (state) {State.activeNote.favorite= !State.activeNote.favorite}, Set_active_note (state, NOTE) {state.activenote=Note}} Const getters={notes:state=state.notes, Activenote:state=State.activenote, Activenotetext:state=State.activenote.text}exportdefault NewVuex.store ({State, mutations, actions, getters})

The original sample file is not getters written to store.js, but is defined directly in the component. To be clearer, I copied the official example and wrote it in Store.js, which makes it easier to invoke it in a component. Then also introduced Action.js, and as an actions object to pass to Vuex.store() , this is VUEX standard notation, for later in the component call more advantageous.

It is important to note that the DELETE_NOTE (state){} original example uses the method provided by Vue1 remove , but this method is removed from the vue2. If you think about it, you'll understand that the function is to delete the elements in the notes array. The native method can be used splice . If JS Foundation is solid, here should be well understood, there is no big problem. Next to the original example, add a post-delete action judgment.

I've never understood the concept of flux before, and it feels like something new, completely unaware of its purpose and role. Change to Vuex, still a little bit of a blur. But by modifying this example, it's basically a kind of enlightened. These things themselves are not mysterious, think about, if we do not use the framework, but to write a todomvc ourselves how to do? It should also be the idea of defining an notes array variable as well as a activeNote variable. Then create some way to change the state. I encountered a situation in the interview, the interviewer repeatedly asked me why I need to use the framework, with JQuery is not also possible to achieve it? This is true, the original method of course can be done, but the code structure will be redundant or messy, lack of small and beautiful features. The framework and design patterns are integrated into the code, which is friendly to a curd application and is easier and easier to implement. My understanding of Vuex is that it is an object that encapsulates the methods and properties associated with the state. The so-called state is the change after the click, the button and other operations.

Using Vuex in Components

Take a look at Toolbar.vue this component first. The modified code is as follows:

 <template> <div id= "Toolbar" > <i @click = "Addnote" class= "Glyphicon glyphicon-plus" ></i> <i @click = "Togglefavorite"  =" Glyphicon Glyphicon-star ": Class  = "{starred:activeNote.favorite}" ></i> <i @click = "Deletenote" class= "Glyphicon Glyphico N-remove "></i> </div></template><script>import { Mapgetters, mapactions} from  ' Vuex ' export  default   {computed:mapgetters ([ ' Activenote '  ' Addnote '  ' deletenote '   ' Togglefavorite '  </script> 

By comparing with the original sample code, the difference here is at a glance. I had a long time to figure out what was going on by printing the Vue instance on the console. vuex 1when used in a component, it is getters directly actions attached to the Vuex property, and there are no methods to provide mapGetters and mapActions so on. Instead, Vuex uses mapGetters and mapActions waits for methods to hang the actions method on the Vue instance. In general, the actions are linked to the Vue instance. We talk about the Vue instance from this level, and the change in Vue 2 is the change in its properties. For example, the methods added in methods in Vue1 can be viewed in the properties of the Vue instance $options , and these methods can be found directly in the first-level attribute in Vue2. The Vuex property can be viewed in vue1, but removed in Vue2, and store replaced. As for the other differences, you can compare yourself, in this way, you can deeply understand Vue design ideas.

Assuming that the rest of the components have been changed in this way, we have an error when we run the example with great delight. The problem is on the extension operator ... , webpack-simple This template cannot parse ES6 ... . To this end, I have been tossing for a long time, want to try to modify Webpack configuration file, but the change is too large. I compromised and decided to discard the extension operator and write this method. Of course, if the use of Webpack template is not a problem, this is relatively simple, we finally say.

Handwriting extension operators ... , let's look at mapActions this method first. The mapGetters mapActions simplest way to understand the two functions is to look at the source code of the Vuex and eventually return an object. That store.js is, you get actions some of the methods in the object as needed. The returned object is then disassembled and then hung onto the Vue instance through an extension operator. For example (the following is just one of the use of extension operators, and other uses can refer to other articles):

var obj = {    1,    2,}var methods = {    ... obj} // Console.log (methods) {    1,    2}

After you understand the usage of the extension operator, it's OK. For the sake of simplicity, I use the online parser of the Babel website directly to see the ES5 notation of the extension operator.

//ES5 Implementation extension operator ...var_extends = Object.assign | |function(target) { for(vari = 1; i < arguments.length; i++) {        varSource =Arguments[i];  for(varKeyinchsource) {            if(Object.prototype.hasOwnProperty.call (source, key)) {Target[key]=Source[key]; }         }     }    returntarget;};

The complete Toolbar.vue component code is as follows:

<template> <div id= "Toolbar" > <i @click = "Addnote" class= "Glyphicon glyphicon-plus" ></i> &lt ; I @click = "Togglefavorite"class= "Glyphicon Glyphicon-star": Class= "{starred:activeNote.favorite}" ></i> <i @click = "Deletenote" class= "Glyphicon glyphicon-remove" > </i> <i @click = "_test" class= "Glyphicon glyphicon-remove" ></i> </div></template>< Script>Import {mapgetters, mapactions} from' Vuex '//ES5 Implementation extension operator ...var_extends = Object.assign | |function(target) { for(vari = 1; i < arguments.length; i++) {        varSource =Arguments[i];  for(varKeyinchsource) {            if(Object.prototype.hasOwnProperty.call (source, key)) {Target[key]=Source[key]; }         }     }    returntarget;};varactions =mapactions ([' Addnote ',  ' Deletenote ',  ' Togglefavorite ']);varMethodsobj =_extends ({},actions) exportdefault{computed:mapgetters ([' Activenote ']), methods:methodsobj}</script>

The remaining two sub-components are similar, I believe you have understood my thinking, the specific code is as follows:

NotesList.vue

<template> <div id= "notes-list" > <div id= "list-header" > @click= "show = ' All '": Class= "{Active:show = = = ' All '}" >All Notes</button> </div> <!--Favorites button-to <div class= "Btn-group" role= "group" &G          T <button type= "button" class= "Btn Btn-default"@click= "show = ' Favorites '": Class= "{Active:show = = = ' Favorites '}" >Favorites</button> </div> </div> </div> <!--render NotesinchA list--<div class= "container" > <div class= "list-group" > <a v- for= "Note in Filterednotes"class= "List-group-item" href= "#": Class= "{Active:activenote = = = Note}"@click= "Updateactivenote (note)" > 

{{Note.text.trim (). substring (0, 30)}} Import {mapgetters, mapactions} from' Vuex '//ES5 Implementation extension operator ...var_extends = Object.assign | |function(target) { for(vari = 1; i < arguments.length; i++) { varSource =Arguments[i]; for(varKeyinchsource) { if(Object.prototype.hasOwnProperty.call (source, key)) {Target[key]=Source[key]; } } } returntarget;};varGetters =Mapgetters ([' Activenote ']);varFilters ={filterednotes:function () { if( This. Show = = = ' All '){ return This. $store. state.notes}Else if( This. Show = = = ' Favorites ') { return This. $store. State.notes.filter (Note =note.favorite) }}}varactions = Mapactions ([' Updateactivenote '])varComputedobj =_extends ({},getters,filters);varMethodsobj =_extends ({},actions); exportdefault{data () {return{show:' All '}}, Computed:computedobj, methods:methodsobj}</script>

Editor.vue

<template>  <div id= "Note-editor" >    <textarea      : Value= "Activenotetext"       @input= "Editnote"      class= "Form-control" >    </textarea>  </div></ template><script>' Vuex 'default  {  computed:mapgetters ([ ' Activenotetext '),  methods:mapactions ([' Editnote '])}</script>
Webpack templates

Using Vue-cli's webpack template directly will be much simpler, and you can parse the extension operator directly, and the code will be more concise. I will not say more, directly affixed to the address of GitHub, we do not understand that you can see: https://github.com/nzbin/notes-app-vuejs2-vuex2

Summarize

Finally finished this tutorial, feeling a lot. This example is more typical, learning a lot of people, maybe I am not the first person to rewrite this case, I just share with you some of my experience. Incidentally, in order to rewrite This example and solve these minor problems, we may want to use a lot of resources, such as GitHub, NPM official website, Babel official website, StackOverflow, Vuejs official website, Vuex website, blog and so on. Go back and think about what Vue is, an object, yes, an object that sets up a lot of properties and methods. Why emphasize the importance of object-oriented, perhaps this is the best interpretation, including jQuery, react, other frameworks and so on. Once a problem is encountered, it may be helpful to print the Vue instance on the console and review its properties repeatedly.

Finally, the next article I want to explore the object-oriented CSS, analysis of a few good UI framework, I believe that everyone can write their own CSS framework.

Explore Vuex 2.0 and build a Notepad app with Vuejs 2.0 + VUEX 2.0

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.