Build environment (vue.js 2.x)

The following uses vuE-CLI to build a project, first install vue-CLI

npm install -g vue-cli

Copy the code

After the installation is complete, run Vue -v to check whether the installation is successful. The VUE-CLI version is 2.9.6.

Mixins

Mixins provide a very flexible way to distribute reusable functionality in Vue components. A mixin object can contain any component option. When a component uses mixin, all mixin options are “blended” into the component’s own options.

To put it simply, Mixins are blocks of code that can be reused. Mixins are a feature that can be considered in real-world development if some code is repetitive

Let’s take a look at how Mixins are used in the popular Element-UI framework. By reading element’s source code, we can see that there are four Mixins defined here

With mixins/emitter. Js

// Emittersfunction broadcast(componentName, eventName, params) {
  this.$children.forEach(child => {
    var name = child.$options.componentName;

    if (name === componentName) {
      child.$emit.apply(child, [eventName].concat(params));
    } else{ broadcast.apply(child, [componentName, eventName].concat([params])); }}); }export default {
  methods: {
    dispatch(componentName, eventName, params) {
      var parent = this.$parent || this.$root;
      var name = parent.$options.componentName;

      while(parent && (! name || name ! == componentName)) { parent = parent.$parent;

        if (parent) {
          name = parent.$options.componentName; }}if (parent) {
        parent.$emit.apply(parent, [eventName].concat(params)); } }, broadcast(componentName, eventName, params) { broadcast.call(this, componentName, eventName, params); }}};Copy the code

Then we can search and see that many files are referring to mixins/ Emitters. Js. From this we can see that the style of the page is different, but the execution method and the required data are similar, so we can use mixins

Please refer to the Vue website for some tips on Mixins

So let’s try it out

Vue init webpack vue_demo // enter the projectcdVue-demo // Install NPM installCopy the code

Create a Vue file inactive. Vue in SRC/components/mixinsDemo/inactive Vue

The following code

<template>
    <div class="hello"> <! --> <h2>Inactive Users</h2> <ul> <li style="display:block;" v-for="user in inactiveUsers">Name: {{user.name}}, Age: {{user.age}}</li> 
        </ul>
    </div>
</template>
<script>
    export default {
        name: 'hello'.data () {
            return {
                status: 0,
                users: [
                    {name: 'glo abredit', age: 27, status: 0, created_at: '2017-09-11' },
                    {name: 'gia fella', age: 29, status: 1, created_at: '2017-09-01' },
                    {name: 'ohaneze david', age: 23, status: 0, created_at: '2017-09-09' },
                    {name: 'paul david', age: 21, status: 1, created_at: '2017-09-21' },
                    {name: 'john williams', age: 20, status: 0, created_at: '2017-03-13' },
                    {name: 'mary jokers', age: 28, status: 1, created_at: '2017-09-30' },
                    {name: 'chris aloha', age: 27, status: 0, created_at: '2017-09-19' },
                    {name: 'johnson silva', age: 29, status: 0, created_at: '2017-09-17' },
                    {name: 'sens carlos', age: 26, status: 0, created_at: '2017-09-04' },
                    {name: 'sophia nkom', age: 25, status: 0, created_at: '2017-09-05' },
                    {name: 'jo westley', age: 22, status: 1, created_at: '2017-09-16' },
                    {name: 'sam john', age: 24, status: 0, created_at: '2017-04-01' },
                    {name: 'dia dia', age: 27, status: 1, created_at: '2017-05-08' }
                ]
            }
        }, 
        methods: {
            get_active_or_inactive(){
                var status = this.status;
                return this.users.filter(function(users){
                    return users.status == status;
                });
            },
            filter_by_date(users){
                return users.sort(function(a, b){
                    return a.created_at > b.created_at;
                })
            }
        },
        computed: {
            inactiveUsers: function() {return this.filter_by_date(this.get_active_or_inactive());
            }
        } 
    }
</script>
Copy the code

Notice that in the code, there are two methods:

Get_active_or_inactive Obtains the user based on the status defined by the component.

Filter_by_date returns an array of users based on the created_AT property in ascending order.

Finally, we have the computed properties section, which contains an inactiveUsers array and calls the get_active_or_inactive and filter_by_date functions.

The Vue component above needs to display inactive users. Now we need another component that needs to display active users. The two valence sets will have both the get_ACTIVE_OR_inactive method and the filter_by_date method (repeat).

Create a Vue file Active. Vue in SRC/components/mixinsDemo/Active. Vue

<template>
    <div class="hello"> <! --> <h2>Active Users</h2> <ul> <li style="display:block;" v-for="user in activeUsers">Name: {{user.name}}, Age: {{user.age}}</li> 
        </ul>
    </div>
</template>
<script>
    export default {
        name: 'hello'.data () {
            return {
                status: 1,
                users: [
                    {name: 'glo abredit', age: 27, status: 0, created_at: '2017-09-11' },
                    {name: 'gia fella', age: 29, status: 1, created_at: '2017-09-01' },
                    {name: 'ohaneze david', age: 23, status: 0, created_at: '2017-09-09' },
                    {name: 'paul david', age: 21, status: 1, created_at: '2017-09-21' },
                    {name: 'john williams', age: 20, status: 0, created_at: '2017-03-13' },
                    {name: 'mary jokers', age: 28, status: 1, created_at: '2017-09-30' },
                    {name: 'chris aloha', age: 27, status: 0, created_at: '2017-09-19' },
                    {name: 'johnson silva', age: 29, status: 0, created_at: '2017-09-17' },
                    {name: 'sens carlos', age: 26, status: 0, created_at: '2017-09-04' },
                    {name: 'sophia nkom', age: 25, status: 0, created_at: '2017-09-05' },
                    {name: 'jo westley', age: 22, status: 1, created_at: '2017-09-16' },
                    {name: 'sam john', age: 24, status: 0, created_at: '2017-04-01' },
                    {name: 'dia dia', age: 27, status: 1, created_at: '2017-05-08' }
              ]
            }
        }, 
        methods: {
            get_active_or_inactive(){
                var status = this.status;
                return this.users.filter(function(users){
                    return users.status == status;
                });
            },
            filter_by_date(users){
                return users.sort(function(a, b){
                    return a.created_at > b.created_at;
                })
            }
        },
        computed: {
            activeUsers: function() {return this.filter_by_date(this.get_active_or_inactive());
            }
        } 
    }
</script>
Copy the code

The main changes to the Active component compared to the Inactive component above are:

  • The status property in the data is changed from 0 to 1
  • Calculation property changed from inactiveUsers to activeUsers

Unify duplicate code into Mixins. Create a new file named usermixin.js in SRC /mixins/ usermixin.js

export const userMixin =  {
  	methods: {
	    get_active_or_inactive(){
	      	var status = this.status;
	      	return this.users.filter(function(users){
	            return users.status == status;
	      	});
	    },
	    filter_by_date(users){
	        return users.sort(function(a, b){
	            returna.created_at > b.created_at; })}}}Copy the code

InActive and Active components introduce userMixin

// Inactive component <template> <div class="hello">
        <h2>Inactive Users</h2>
        <ul>
            <li style="display:block;" v-for="user in inactiveUsers">Name: {{user.name}}, Age: {{user.age}}</li> 
        </ul>
      </div>
</template>
<script>
	import {userMixin} from '.. /.. /mixins/userMixin'
    export default {
      	name: 'hello',
      	mixins: [userMixin],
      	data () {
       	    return {
	          	status: 0,
	          	users: [
		            {name: 'glo abredit', age: 27, status: 0, created_at: '2017-09-11' },
		            {name: 'gia fella', age: 29, status: 1, created_at: '2017-09-01' },
		            {name: 'ohaneze david', age: 23, status: 0, created_at: '2017-09-09' },
		            {name: 'paul david', age: 21, status: 1, created_at: '2017-09-21' },
		            {name: 'john williams', age: 20, status: 0, created_at: '2017-03-13' },
		            {name: 'mary jokers', age: 28, status: 1, created_at: '2017-09-30' },
		            {name: 'chris aloha', age: 27, status: 0, created_at: '2017-09-19' },
		            {name: 'johnson silva', age: 29, status: 0, created_at: '2017-09-17' },
		            {name: 'sens carlos', age: 26, status: 0, created_at: '2017-09-04' },
		            {name: 'sophia nkom', age: 25, status: 0, created_at: '2017-09-05' },
		            {name: 'jo westley', age: 22, status: 1, created_at: '2017-09-16' },
		            {name: 'sam john', age: 24, status: 0, created_at: '2017-04-01' },
		            {name: 'dia dia', age: 27, status: 1, created_at: '2017-05-08' }
	          	]
	        }
      	}, 
      	computed: {
	        inactiveUsers: function() {returnthis.filter_by_date(this.get_active_or_inactive()); } } } </script> / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / // Active component <template> <div class="hello"> <! --> <h2>Active Users</h2> <ul> <li style="display:block;" v-for="user in activeUsers">Name: {{user.name}}, Age: {{user.age}}</li> 
        </ul>
      </div>
</template>   
<script>
    import {userMixin} from '.. /.. /mixins/userMixin'
    export default {
	    name: 'hello',
	    mixins: [userMixin],
	    data () {
	        return {
	         	status: 1,
	          	users: [
		            {name: 'glo abredit', age: 27, status: 0, created_at: '2017-09-11' },
		            {name: 'gia fella', age: 29, status: 1, created_at: '2017-09-01' },
		            {name: 'ohaneze david', age: 23, status: 0, created_at: '2017-09-09' },
		            {name: 'paul david', age: 21, status: 1, created_at: '2017-09-21' },
		            {name: 'john williams', age: 20, status: 0, created_at: '2017-03-13' },
		            {name: 'mary jokers', age: 28, status: 1, created_at: '2017-09-30' },
		            {name: 'chris aloha', age: 27, status: 0, created_at: '2017-09-19' },
		            {name: 'johnson silva', age: 29, status: 0, created_at: '2017-09-17' },
		            {name: 'sens carlos', age: 26, status: 0, created_at: '2017-09-04' },
		            {name: 'sophia nkom', age: 25, status: 0, created_at: '2017-09-05' },
		            {name: 'jo westley', age: 22, status: 1, created_at: '2017-09-16' },
		            {name: 'sam john', age: 24, status: 0, created_at: '2017-04-01' },
		            {name: 'dia dia', age: 27, status: 1, created_at: '2017-05-08' }
	          	]
	        }
	    }, 
      	computed: {
	        activeUsers: function() {return this.filter_by_date(this.get_active_or_inactive());
	        }
      	} 
    }
</script>
Copy the code

Looking at the two components above, the difference is that:

  • We no longer have methods in our component
  • We added Mixins imports to the Vue component
 import {userMixin} from '.. /.. /mixins/userMixin'
Copy the code
  • We refer to mixins on the mixins property of our component
mixins: [userMixin]
Copy the code

Let’s see if the code works and replace app.vue with the following

<template>
    <div id="app">
	    <img src="./assets/logo.png">
	    <active/>
	    <inactive/>
    </div>
</template>

<script>
import Active from './components/mixinsDemo/active'
import Inactive from './components/mixinsDemo/inactive'
export default {
	name: 'App',
	components: {
	    Active,
	    Inactive
	}
}
</script>

<style>
#app {
	font-family: 'Avenir', Helvetica, Arial, sans-serif;
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
	text-align: center;
	color: #2c3e50;
	margin-top: 60px;
}
</style>

Copy the code

If we run the NPM run dev command on a terminal and browse to http://localhost:8080/, we should see the following:

Custom instruction

Everyone who writes a Vue application has probably heard of directives and used them, such as V-if, V-for, v-show. In addition to the core function default built-in instructions, Vue also allows the registration of custom instructions.

When to use custom directives to perform low-level operations on ordinary DOM elements

Continue with the code from the previous project

Create a Vue file directive. Vue in SRC/components/directivesDemo/directive. The Vue used to test our custom commands

Js file store to create a new custom instructions myDirective. Js in SRC/directives/myDirective Js

// myDirective.js
import Vue from 'vue'

Vue.directive('test'{// When the bound element is inserted into the DOM... inserted:function(el) {// Change element color and background color el.style.color ='white';
        el.style.background = 'blue' 
        var Base64 = {
                _keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
                encode:function(e){
                        var t=""; var n,r,i,s,o,u,a; var f=0; e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++); r=e.charCodeAt(f++); i=e.charCodeAt(f++); s=n>>2; o=(n&3)<<4|r>>4; u=(r&15)<<2|i>>6; a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){
                                        a=64
                                }
                                t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)
                        }
                        return t
                },
                _utf8_encode:function(e){
                        e=e.replace(/rn/g,"n");
                        var t="";
                        for(var n=0; n<e.length; n++){ var r=e.charCodeAt(n);if(r<128){
                                        t+=String.fromCharCode(r)
                                }else if(r>127&&r<2048){
                                        t+=String.fromCharCode(r>>6|192);
                                        t+=String.fromCharCode(r&63|128)
                                }else{
                                        t+=String.fromCharCode(r>>12|224);
                                        t+=String.fromCharCode(r>>6&63|128);
                                        t+=String.fromCharCode(r&63|128)
                                }
                        }
                        returnT}} // Insert el.innerhtml = base64.encode (el.innerhtml); }})Copy the code

In the above directive, we listen for the Inserted hook function when the tied element is inserted into the DOM. We modify the color and background style attributes of the bound element. Next, we define a function that decodes the string into base64 encoding, and then our bound element calls the Base64 encoding function. Now you might be wondering, where exactly does the inserted hook function come from?

The following hook functions are provided in the Vue documentation:

An instruction definition object can provide the following hook functions (all optional) :

  • Bind: Called only once, the first time a directive is bound to an element. This is where you can perform one-time initialization Settings.

  • Inserted: Called when the bound element is inserted into a parent (the parent is guaranteed to exist, but not necessarily inserted into the document).

  • Update: called when the component’s VNode is updated, but may occur before its child VNodes are updated. The value of the instruction may or may not have changed. But you can ignore unnecessary template updates by comparing the values before and after the update

  • ComponentUpdated: Invoked when the VNode of the component where the directive resides and its child VNodes are all updated.

  • Unbind: Called only once, when an instruction is unbound from an element.

Basically, what we call hooks depends a lot on when and how we want our actions to happen. In this directive, we want it to happen after the element is inserted into its parent.

Test the new instruction, we just write the SRC/components/directivesDemo/directive. The vue

<template>
     <div class="test">
        <p v-test>test1</p>
        <p v-test>test2</p>
     </div>
</template>
<script>
	export default {}
</script>
Copy the code

Replace the following code in the file SRC/app.vue

<template>
  	<div id="app">
            <img src="./assets/logo.png">
            <active/>
            <inactive/>
            <directive/>
  	</div>
</template>

<script>
import Active from './components/mixinsDemo/active'
import Inactive from './components/mixinsDemo/inactive'
import directive from './components/directivesDemo/directive'
export default {
	name: 'App',
	components: {
	    Active,
	    Inactive,
	    directive
	}
}
</script>

<style>
#app {
	font-family: 'Avenir', Helvetica, Arial, sans-serif;
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
	text-align: center;
	color: #2c3e50;
	margin-top: 60px;
}
</style>
Copy the code

Replace the following code in the file SRC /main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import '@/directives/myDirective'
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})
Copy the code

Run NPM run dev

The filter

A Vue filter is essentially a function that takes a value, processes it, and returns the processed value.

Filters can be used in two places: double curly brace interpolation and v-bind expressions (the latter supported as of 2.1.0+). The end of the filter should be added in the JavaScript expression, by “pipe (|)” symbol indicates:

<! - in a pair of curly braces - > {{message | capitalize}} <! -- in 'v-bind' --> <div v-bind:id="rawId | formatId"></div>
Copy the code

You can define local filters in a component option:

filters: {
  capitalize: function (value) {
    if(! value)return ' '
    value = value.toString()
    return value.charAt(0).toUpperCase() + value.slice(1)
  }
}
Copy the code

Or define filters globally before creating Vue instances:

Vue.filter('capitalize'.function (value) {
  if(! value)return ' '
  value = value.toString()
  return value.charAt(0).toUpperCase() + value.slice(1)
})

new Vue({
  // ...
})
Copy the code

The filter function always takes the value of the expression (the result of the previous chain of operations) as its first argument. In the example above, the Capitalize filter function will receive the value of Message as its first argument.

Filters can be connected in series:

{{ message | filterA | filterB }}
Copy the code

In this example, filterA is defined as a filter function that receives a single parameter, and the value of the expression Message is passed into the function as a parameter. It then proceeds to call filterB, which is also defined to receive a single argument, passing the result of filterA to filterB.

Filters are JavaScript functions, so they can accept arguments:

{{ message | filterA('arg1', arg2) }}
Copy the code

Here, filterA is defined as a filter function that takes three arguments. The value of message is the first argument, the plain string ‘arg1’ is the second argument, and the value of the expression arg2 is the third argument.

Let’s actually write a filter so that each word starts with a capital letter

Create a Vue file filter. Vue in SRC/components/filtersDemo/filter. The Vue is used to test our custom commands

Create a filter.js file to store the filters in SRC /filters/myfilter.js

// src/filters/myfilter.js
import Vue from 'vue'

Vue.filter('camel'.function(str){
        return str.toLowerCase().replace(/^\w|\s\w/g, function (letter) {
        returnletter.toUpperCase(); })})Copy the code

Test the filter, we just write the SRC/components/filtersDemo/filter. The vue

<template>
    <div class="test">
        <p>testFilter</p>
        <p>{{msg | camel}}</p>
    </div>
</template>
<script>
	export default {
		data() {
			return {
				msg: 'the first letter of every word is capitalized'
			}
		}
	}
</script>
Copy the code

Replace the following code in the file SRC/app.vue

<template>
  	<div id="app">
	    <img src="./assets/logo.png">
	    <active/>
	    <inactive/>
	    <directive/>
	    <myFilter/>
  	</div>
</template>

<script>
import Active from './components/mixinsDemo/active'
import Inactive from './components/mixinsDemo/inactive'
import directive from './components/directivesDemo/directive'
import myFilter from './components/filtersDemo/filter'
export default {
	name: 'App',
	components: {
	    Active,
	    Inactive,
	    directive,
	    myFilter
	}
}
</script>

<style>
#app {
	font-family: 'Avenir', Helvetica, Arial, sans-serif;
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
	text-align: center;
	color: #2c3e50;
	margin-top: 60px;
}
</style>

Copy the code

Replace the following code in the file SRC /main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import '@/directives/myDirective'
import '@/filters/myFilter'
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

Copy the code

Run NPM run dev

Transition (in/out)

Vue provides a variety of different application transitions when inserting, updating, or removing the DOM.

The easiest way to implement transitions on a page is through Vue’s < Transition > component. The < Transition > component is a global component of Vue and can be used directly.

Vue transitions work by adding and removing classes on elements when inserting, updating, or removing the DOM.

There are six different class prefixes for handling transitions:

  • -Enter: Contains the style in which the element begins to appear in the scene
  • -leave: contains the style of when the element starts to leave the scene
  • -enter-active: indicates the conversion mode, such as conversion seconds
  • -leave-active: specifies the style of the invalid conversion, such as the conversion seconds
  • -leave-to: This replaces -leave
  • – Enter -to: This is the end class of Enter. It is applied when -enter is deleted

For example, if we had a transition named test, we could use them like this:

<div>
  <transition name="test">
    <p v-if="show">hello</p>
  </transition>
</div>
Copy the code
.test-enter-active {
    transition: transform 3s;
    text-shadow:0px 5px 10px #fdff00;
}
.test-leave-active {
    transition: transform 3s;
    text-shadow:0px 5px 10px #a1a194;
}
.test-enter, .test-leave-to {
    transform: translateX(90%);
}
.test-enter-to, .test-leave {
    transform: translateX(-15%);
}
Copy the code

See the Vue website for advanced uses of some transitions

So let’s do an example

Create a Vue file transtion. Vue in SRC/components/transtionDemo/transition. The Vue used to demonstrate the transition

<template>
    <div class="hello">
     	<transition name="test">
        	<h1 v-if="status">{{ msg }}</h1>
        </transition>
        <input type="button" @click="status=! status" value="test transition"/>
    </div>
</template>
<script>
    export default {
      	name: 'HelloWorld'.data () {
	        return {
	          	msg: 'welcome to your Vue.js App',
	          	status: false
	        }
      	},
     	mounted: function(){
        	this.status = true;
      	}
    }
</script>
<style>
    h1, h2 {
      	font-weight: normal;
    }
    
    ul {
      	list-style-type: none;
      	padding: 0;
    }
    
    li {
        display: inline-block;
        margin: 0 10px;
    }
    
    a {
      	color: #42b983;
    }
    
    .test-enter-active {
	      transition: transform 3s;
	      text-shadow:0px 5px 10px #fdff00;
    }
    .test-leave-active {
        transition: transform 3s;
        text-shadow:0px 5px 10px #a1a194;
    }
    
    .test-enter, .test-leave-to {
      	transform: translateX(90%);
    }
    
    .test-enter-to, .test-leave {
      	transform: translateX(-15%);
    }
</style>
Copy the code

Replace the following code in the file SRC/app.vue

<template>
  	<div id="app">
	    <img src="./assets/logo.png">
	  	<active/>
	  	<inactive/>
	  	<directive/>
	  	<myFilter/>
	  	<myTranstion/>
  	</div>
</template>

<script>
import Active from './components/mixinsDemo/active'
import Inactive from './components/mixinsDemo/inactive'
import directive from './components/directivesDemo/directive'
import myFilter from './components/filtersDemo/filter'
import myTranstion from './components/transtionDemo/transtion'
export default {
	name: 'App',
	components: {
	    Active,
	    Inactive,
	    directive,
	    myFilter,
	    myTranstion
	}
}
</script>

<style>
#app {
	font-family: 'Avenir', Helvetica, Arial, sans-serif;
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
	text-align: center;
	color: #2c3e50;
	margin-top: 60px;
}
</style>

Copy the code

Run NPM run dev

State management

As your Vue application becomes larger and composed of multiple components, you may encounter problems with how to share data across components and ensure that components that use the same data are always updated when the data changes.

The complexity of large applications generally increases as multiple components are scattered among many components and interact with each other. To solve this problem, Vue offers vuex

What is Vuex?

According to the official Vuex document, Vuex is a state management mode specially developed for vuue.js applications. It uses centralized storage to manage the state of all components of the application, and the corresponding rules ensure that the state changes in a predictable way. Vuex state self-management application consists of the following parts:

  • State: Data source that drives the application
  • Getters: Used to access data from the state management repository
  • Mutations: A processor function that performs data changes in a state tree
  • Actions: Submit the Mutations function. Mutations differ from Actions in that Actions can include asynchronous operations

Let’s write a demo to try it out

Let’s go back to the last project

The VUEX library needs to be installed

npm install vuex -S
Copy the code

With Vuex installed, let’s see how state, Actions, mutations, and getters work.

1. State the data source

state: {
    users: [
        {name: 'glo abredit', age: 27, status: 0, created_at: '2017-09-11' },
        {name: 'gia fella', age: 29, status: 1, created_at: '2017-09-01' },
        {name: 'ohaneze david', age: 23, status: 0, created_at: '2017-09-09' },
        {name: 'paul david', age: 21, status: 1, created_at: '2017-09-21' },
        {name: 'john williams', age: 20, status: 0, created_at: '2017-03-13' },
        {name: 'mary jokers', age: 28, status: 1, created_at: '2017-09-30' },
        {name: 'chris aloha', age: 27, status: 0, created_at: '2017-09-19' },
        {name: 'johnson silva', age: 29, status: 0, created_at: '2017-09-17' },
        {name: 'sens carlos', age: 26, status: 0, created_at: '2017-09-04' },
        {name: 'sophia nkom', age: 25, status: 0, created_at: '2017-09-05' },
        {name: 'jo westley', age: 22, status: 1, created_at: '2017-09-16' },
        {name: 'sam john', age: 24, status: 0, created_at: '2017-04-01' },
        {name: 'dia dia', age: 27, status: 1, created_at: '2017-05-08'}}]Copy the code

When we explain what a state is, we say that it is an object that contains data. In the above code, we can see that it is an object containing an array of users.

2.Action

actions: {
  ADD_USER: function({ commit }, new_user) {
    commit("ADD_USER_MUTATION", new_user);
  },
  DELETE_USER: function({ commit }, user_id) {
    commit("DELETE_USER_MUTATION", user_id); }}Copy the code

In our Actions section, we define two functions:

ADD_USER: This function delivers an ADD_USER_MUTATION mutations operation, which adds a new user to the list.

DELETE_USER: This function delivers a DELETE_USER_MUTATION mutations operation, which removes the user from the list.

3.mutations

mutations: {
  ADD_USER_MUTATION: function(state, new_user) {
    state.users.push(new_user);
  },
  DELETE_USER_MUTATION: function(state, user_id) { state.users.splice(user_id,1); }}Copy the code

In the above code, they directly change the state of the state store. Examining the code, we notice two features:

ADD_USER_MUTATION: This mutation pushes the new user to our list of users DELETE_USER_MUTATION: This mutation removes the user from the array of users based on the id passed (the index used for this object).

4.getter

getters: {
  users: state => {
    returnstate.users; }}Copy the code

In our getters, we define a function:

Users: This getter returns all the users of our state library next, let’s merge these concepts together to create our Vuex state management library. Create a new file SRC /store.js

import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const store = new Vuex.Store({         
        state: {
              users: [
                {name: 'glo abredit', age: 27, status: 0, created_at: '2017-09-11' },
                {name: 'gia fella', age: 29, status: 1, created_at: '2017-09-01' },
                {name: 'ohaneze david', age: 23, status: 0, created_at: '2017-09-09' },
                {name: 'paul david', age: 21, status: 1, created_at: '2017-09-21' },
                {name: 'john williams', age: 20, status: 0, created_at: '2017-03-13' },
                {name: 'mary jokers', age: 28, status: 1, created_at: '2017-09-30' },
                {name: 'chris aloha', age: 27, status: 0, created_at: '2017-09-19' },
                {name: 'johnson silva', age: 29, status: 0, created_at: '2017-09-17' },
                {name: 'sens carlos', age: 26, status: 0, created_at: '2017-09-04' },
                {name: 'sophia nkom', age: 25, status: 0, created_at: '2017-09-05' },
                {name: 'jo westley', age: 22, status: 1, created_at: '2017-09-16' },
                {name: 'sam john', age: 24, status: 0, created_at: '2017-04-01' },
                {name: 'dia dia', age: 27, status: 1, created_at: '2017-05-08' }
              ]
            },
        actions: {
              ADD_USER: function({ commit }, new_user) {
                commit("ADD_USER_MUTATION", new_user);
              },
              DELETE_USER: function({ commit }, user_id) {
                commit("DELETE_USER_MUTATION", user_id);
              }
            },

        mutations: {
              ADD_USER_MUTATION: function(state, new_user) {
                state.users.push(new_user);
              },
              DELETE_USER_MUTATION: function(state, user_id) {
                state.users.splice(user_id,1);
              }
            },

        getters: {
              users: state => {
               returnstate.users; }}});export default store;
Copy the code

This is how easy it is to set up the Vuex state management library. Let’s start using the state management library in our application.

We need to pass the state management library to our Vue instance. To do this, replace the following with: SRC /main.js.

import Vue from 'vue'
import App from './App'
import router from './router'
import '@/directives/myDirective'
import '@/filters/myFilter'
import store from './store'
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

Copy the code

In the above code, we import the Store component and pass it to our Vue component.

Create a Vue file store. Vue in SRC/components/storeDemo/store. Vue is used to demonstrate vuex

<template>
    <div class="store-demo">
	<input type="text" v-model="user.name" placeholder="Name"/>
	<input type="text" v-model="user.age" placeholder="age"/>
	<input type="text" v-model="user.status" placeholder="status"/>
	<input type="text" v-model="user.created_at" placeholder="created_at"/>
	<input type="button" @click="add_user()" :disabled="(user.name =='')" value="add user"/>
	</hr>    
	<h2>Users</h2>
	<ul>
	    <li style="display:block;" v-for="(use, index) in users">Name: {{use.name}}, Age: {{use.age}}     <input type="button" value="delete user" @click="delete_user(index)" /></li> 
	</ul>
    </div>
</template>
    
<script>
    export default {
      	data () {
            return {
                msg: 'Welcome to Your Vue.js App',
                user: {
                    name: ' ',
                    age: ' ',
                    status: 0,
                    created_at: '2019-06-21'      
                }
            }
      	},
      	methods: {
	    add_user() {
                this.$store.dispatch('ADD_USER', this.user);
              	this.user =  {
                    name: ' ',
                    age: ' ',
                    status: 0,
                    created_at: '2019-06-21'      
             	}
        	},
        	delete_user (index){
      		    this.$store.dispatch('DELETE_USER', index);
        	}
      	},
      	computed: {
            users() {return this.$store.getters.users;
            }
        }
    }
</script>
<style scoped>
    h1, h2 {
      	font-weight: normal;
    }
    
    ul {
      	list-style-type: none;
      	padding: 0;
    }
    
    li {
      	display: inline-block;
      	margin: 0 10px;
    }
    
    a {
      	color: #42b983;
    }
</style>
Copy the code

Introduced in the SRC/App. Vue SRC/components/storeDemo/store. Vue components

<template>
  	<div id="app">
	    <img src="./assets/logo.png">
	  	<active/>
	  	<inactive/>
	  	<directive/>
	  	<myFilter/>
	  	<myTranstion/>
	  	<myStore/>
  	</div>
</template>

<script>
import Active from './components/mixinsDemo/active'
import Inactive from './components/mixinsDemo/inactive'
import directive from './components/directivesDemo/directive'
import myFilter from './components/filtersDemo/filter'
import myTranstion from './components/transtionDemo/transtion'
import myStore from './components/storeDemo/store'
export default {
	name: 'App',
	components: {
	    Active,
	    Inactive,
	    directive,
	    myFilter,
	    myTranstion,
	    myStore
	}
}
</script>

<style>
#app {
	font-family: 'Avenir', Helvetica, Arial, sans-serif;
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
	text-align: center;
	color: #2c3e50;
	margin-top: 60px;
}
</style>

Copy the code

In the SRC/components/storeDemo/store. Vue code, we will notice the two functions:

Add_user: This method calls add_user in vuex to add a new member to the User object

Delete_user: This method calls delete_user in vuex to delete a member from the User object by id

Here we call getters to evaluate the properties. This function returns all users in the store.

Run NPM run dev and the result is as follows:

Server-side rendering

One disadvantage of Vue is that the page is not visible until the browser executes the application’s JavaScript package. This causes the application to render a blank page, and in some cases, the preloader to remain displayed for a very long time. The Vue team tried to solve this problem and came up with a server-side rendering called SSR. Through server rendering, SEO fetching can be optimized, and home page loading speed can be improved. For more information on Vue SSR, visit the Vue SSR Guide

Refer to the article

  • Advanced Vue.js concepts
  • Vue website