vue

Course is an introduction to

First 5 days: learning the basic grammar and concepts of Vue; The last 5 days: project-driven teaching;

What is a Vue. Js

  • React is the most popular front-end framework. (React can be used to develop mobile apps as well as websites. Vue syntax can also be used for mobile App development, which requires Weex.)

  • Vue.js is one of the mainstream frameworks for the front end. Along with Angular.js and react. js, vue. js is one of the top three front-end frameworks!

  • Vue.js is a set of frameworks for building user interfaces, focusing only on the view layer. It is not only easy to get started, but also easy to integrate with third-party libraries or existing projects. (Vue has supporting third-party class libraries, which can be integrated to do large-scale project development)

  • The main work of the front end? Mainly responsible for the V layer of MVC; The main work is to deal with the interface, to make the front page effect;

Why study popular frameworks

  • In order to improve the development efficiency of enterprises: in enterprises, time is efficiency and efficiency is money;
  • In the enterprise, using frameworks can improve the efficiency of development;
  • The process of improving development efficiency: native JS -> libraries like Jquery -> front-end template engine -> Angular. JS/vue.js (helps reduce unnecessary DOM manipulation; Improve rendering efficiency; The concept of bi-directional data binding (with instructions provided by the framework, we front-end programmers only need to care about the business logic of the data, not how the DOM is rendered)

  • In Vue, one of the core concepts is that users no longer manipulate DOM elements, freeing users’ hands and allowing programmers to focus more time on business logic.

  • Enhance the competitiveness of their employment

  • People have no I have, people have my excellent
  • What do you do when you’re not busy?

The difference between frameworks and libraries

  • Framework: a complete set of solutions; If the project needs to change the framework, it needs to rebuild the whole project.
  • Express in Node;
  • Libraries (plug-ins) : Provide a small function that is less intrusive to the project. If a library fails to fulfill certain requirements, it can be easily switched to another library to fulfill them.
    1. Switch from Jquery to Zepto
    1. Switch from EJS to Art-Template

The difference between MVC in Node (back end) and MVVM in the front end

  • MVC is a back-end layered development concept;

  • MVVM is the concept of the front View layer, which mainly focuses on the separation of the View layer. That is to say, MVVM divides the front View layer into three parts: Model, View and VM ViewModel

  • Why do you have MVVM when you have MVC

The mapping between vue.js base code and MVVM

The Vue –Basic code structureandInterpolation expression,v-cloak

Vue of instructionv-textandv-html

Vue of instructionv-bindThree usages of

  1. Use the instruction V-bind directly

  2. Using simplified instructions:

  3. When binding, concatenate binding contents: :title=”btnTitle + ‘, which is appended ‘”

Vue of instructionv-onandRunning horse light effect

Running horse light effect

  1. HTML structure:

<div id="app">

    <p>{{info}}</p>

 <input type="button" value="Open" v-on:click="go">   <input type="button" value="Stop" v-on:click="stop">   </div>  Copy the code
  1. Vue instances:

// Create Vue instance, get ViewModel
    var vm = new Vue({

 el: '#app'.  data: {   info: 'Obscene development, don't wave ~! '.  intervalId: null   },   methods: {   go() {  // If a timer is running, run thereturn   if(this.intervalId ! = null) {  return;   }  // Start timer  this.intervalId = setInterval(() => {   this.info = this.info.substring(1) + this.info.substring(0, 1);   }, 500);   },   stop() {   clearInterval(this.intervalId);   }   }   });  Copy the code

Vue of instructionThe abbreviation of v - onandEvent modifier

Event modifiers:

  • .stop prevents bubbling

  • . Prevent Prevents default events

  • .capture Uses event capture mode when adding event listeners

  • .self fires the callback only if the event fires on the element itself (such as when it is not a child element)

  • The. Once event is triggered only once

Vue of instructionv-modelandTwo-way data binding

Simple Calculator case

  1. HTML code structure

  <div id="app">

    <input type="text" v-model="n1">

 <select v-model="opt">   <option value="0">+</option>   <option value="1">-</option>   <option value="2">*</option>   <option value="3"> present < option >  </select>   <input type="text" v-model="n2">   <input type="button" value="=" v-on:click="getResult">   <input type="text" v-model="result">   </div>  Copy the code
  1. Vue example code:

// Create Vue instance, get ViewModel
    var vm = new Vue({

 el: '#app'.  data: {   n1: 0,   n2: 0,   result: 0,   opt: '0'   },   methods: {   getResult() {   switch (this.opt) {   case '0':   this.result = parseInt(this.n1) + parseInt(this.n2);   break;   case '1':   this.result = parseInt(this.n1) - parseInt(this.n2);   break;   case '2':   this.result = parseInt(this.n1) * parseInt(this.n2);   break;   case '3':   this.result = parseInt(this.n1) / parseInt(this.n2);   break;   }   }   }   });  Copy the code

Use styles in Vue

Using class styles

  1. An array of
<h1 :class="['red', 'thin']"> This is a wicked H1</ H1 >Copy the code
  1. Arrays use ternary expressions
<h1 :class="['red', 'thin', isactive?'active':'']"> This is a wicked H1</ H1 >Copy the code
  1. Array with nested objects
<h1 :class="['red', 'thin', {'active': isactive}]"> This is a wicked H1</ H1 >Copy the code
  1. Working directly with objects
<h1 :class="{red:true, italic:true, active:true, thin:true}"> This is a wicked H1</ H1 >Copy the code

Use inline styles

  1. It passes directly over the element:styleWrite style objects in the form of
<h1 :style="{color: 'red', 'font-size': '40px'}"> This is a kind H1</ H1 >Copy the code
  1. Define the style object todata, and directly referenced to:style
  • Define styles on data:
data: {
        h1StyleObj: { color: 'red'.'font-size': '40px'.'font-weight': '200' }
}
Copy the code
  • Within an element, style objects are applied to the element in the form of attribute bindings:
<h1 :style="h1StyleObj"> This is a kind H1</ H1 >Copy the code
  1. in:styleThrough an array, reference multipledataThe style object on
  • Define styles on data:
data: {
        h1StyleObj: { color: 'red'.'font-size': '40px'.'font-weight': '200' },
        h1StyleObj2: { fontStyle: 'italic' }
}
Copy the code
  • Within an element, style objects are applied to the element in the form of attribute bindings:
<h1 :style="[h1StyleObj, h1StyleObj2]"> This is a kind H1</ H1 >Copy the code

Vue of instructionv-forandkeyattribute

  1. Iterative array
<ul>
  <li v-for="(item, i) in list"> index: {{I}} - name: {{item. The name}} - age: {{item. Age}} < / li ></ul>
Copy the code
  1. Iterate over properties in an object

<! Loop over properties on the object -->
    <div v-for="(val, key, i) in userInfo">{{val}} --- {{key}} --- {{i}}</div>

Copy the code
  1. The iteration number

<p v-for="i in 10"> This is the {{I}} P tag </ P >
Copy the code

In version 2.2.0+, keys are now required when using V-for in components.

When vue.js is updating a rendered element list with V-for, it defaults to a “reuse in place” strategy. If the order of data items is changed, instead of moving DOM elements to match the order of data items, Vue simply reuses each element here and ensures that it displays every element that has been rendered under a specific index.

To give Vue a hint that it can track the identity of each node to reuse and reorder existing elements, you need to provide a unique key attribute for each item.

Vue of instructionv-ifandv-show

In general, V-if has a higher switching cost and V-show has a higher initial rendering cost. Therefore, v-show is better if you need to switch frequently, and v-if is better if conditions are unlikely to change at run time.

Brand Management Cases

Add a new brand

Delete the brand

Select brands according to the criteria

  1. The filterBy directive in 1.x was deprecated in 2.x:

FilterBy – instruction


<tr v-for="item in list | filterBy searchName in 'name'">

  <td>{{item.id}}</td>

 <td>{{item.name}}</td>   <td>{{item.ctime}}</td>   <td>   <a href="#" @click.prevent="del(item.id)"> delete < / a >  </td>  </tr>  Copy the code
  1. How to implement filtering manually in 2.x:
  • The filter box is bound to the VM instancesearchNameProperties:

<hr> Enter the filter name:
<input type="text" v-model="searchName">

Copy the code
  • In the use ofv-forInstructions are no longer direct when looping over each row of dataitem in list, butinA filter methods method, at the same time, the filter conditionssearchNamePass in:

<tbody>

      <tr v-for="item in search(searchName)">

 <td>{{item.id}}</td>   <td>{{item.name}}</td>   <td>{{item.ctime}}</td>   <td>   <a href="#" @click.prevent="del(item.id)"> delete < / a >  </td>   </tr>   </tbody>  Copy the code
  • searchIn the filter method, use the arrayfilterMethods:

search(name) {

  return this.list.filter(x => {

 return x.name.indexOf(name) != -1;   });  }  Copy the code

Vue debugging toolvue-devtoolsInstallation steps and use of

Vue.js DevTools-FanQiang installation mode – Recommended

The filter

Concept: Vue.js allows you to customize filters that can be used for some common text formatting. Filters can be used in two places: Mustache interpolation and V-bind expressions. Filters should be added to the end of JavaScript expressions, indicated by “pipes”;

Private filter

  1. The HTML element:

<td>{{item.ctime | dataFormat('yyyy-mm-dd')}}</td>

Copy the code
  1. privatefiltersDefinition method:

Filters: {// Private local filters that can only be used in the View area controlled by the current VM object
    dataFormat(input, pattern = "") {// Pass pattern= in the parameter list""To specify parameter defaults to prevent errors
 var dt = new Date(input);  // Get the date  var y = dt.getFullYear();   var m = (dt.getMonth() + 1).toString().padStart(2, '0');   var d = dt.getDate().toString().padStart(2, '0');    // If the string type passed in, lowercase, equals YYYY-MM-dd, return year-month-day // Otherwise, return year - month - day time: minute: second  if (pattern.toLowerCase() === 'yyyy-mm-dd') {   return `${y}-${m}-${d}`;   } else {  // Get the minutes and seconds  var hh = dt.getHours().toString().padStart(2, '0');   var mm = dt.getMinutes().toString().padStart(2, '0');   var ss = dt.getSeconds().toString().padStart(2, '0');     return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;   }   }   }  Copy the code

Using the new method String String ES6. Prototype. PadStart (maxLength, fillString = ‘ ‘) or String. Prototype. PadEnd (maxLength, FillString = “) to fill the string;

Global filter


// Define a global filter
Vue.filter('dataFormat'.function (input, pattern = ' ') {

 var dt = new Date(input);  // Get the date  var y = dt.getFullYear();   var m = (dt.getMonth() + 1).toString().padStart(2, '0');   var d = dt.getDate().toString().padStart(2, '0');    // If the string type passed in, lowercase, equals YYYY-MM-dd, return year-month-day // Otherwise, return year - month - day time: minute: second  if (pattern.toLowerCase() === 'yyyy-mm-dd') {   return `${y}-${m}-${d}`;   } else {  // Get the minutes and seconds  var hh = dt.getHours().toString().padStart(2, '0');   var mm = dt.getMinutes().toString().padStart(2, '0');   var ss = dt.getSeconds().toString().padStart(2, '0');     return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;   }  });  Copy the code

Note: When there are two filters with the same name, local and global filters are called using the nearest principle, i.e. local filters are called before global filters!

Keyboard modifiers and custom keyboard modifiers

1. Custom keyboard modifiers in x


Vue.directive('on').keyCodes.f2 = 113;

Copy the code

2. Customize keyboard modifiers in x

  1. throughVue.config.keycodes. name = key valueAliases from defining case modifiers:

Vue.config.keyCodes.f2 = 113;

Copy the code
  1. Use custom keystroke modifiers:

<input type="text" v-model="name" @keyup.f2="add">

Copy the code

Custom instruction

  1. Custom global and local custom directives:

// Define the global directive v-focus to automatically get focus for the bound element:
    Vue.directive('focus', {

 inserted: function(el) {// INSERTED: Called when the bound element is inserted into the parent node  el.focus();   }   });    // Customize the local directives v-color and v-font-weight to set the specified font color and font weight for the bound elements:  directives: {  Color: {// Sets the specified font for the element  bind(el, binding) {   el.style.color = binding.value;   }   },   'font-weight': function(el, binding2) {// Short form of custom instruction, equivalent to definitionbindAnd update hook functions  el.style.fontWeight = binding2.value;   }   }  Copy the code
  1. How to use custom instructions:

<input type="text" v-model="searchName" v-focus v-color="'red'" v-font-weight="900">

Copy the code

Custom element instruction in Vue 1.x

Vue.elementDirective('red-color', {
  bind: function () {
    this.el.style.color = 'red';
  }
});
Copy the code

Usage:

<red-color>1232</red-color>
Copy the code

Finally sing


This article is formatted using MDNICE