Introduction: This article takes you through the vue.js framework, why to use Vue and a few simple instructions. The first time to write study notes, digging friends, if there are some mistakes in the article to remind me, thanks a lot!

What is a Vue

Vue is a set of progressive frameworks for building user interfaces. Vue is designed to be applied layer by layer from the bottom up. Responsive update mechanism: When data changes, the view automatically refreshes.

The MVVM pattern

  • Model: Responsible for the data storage (the data Model that contains the business and validation logic)
  • View: Responsible for the presentation, layout and appearance of the page
  • View Model: Responsible for business logic processing (such as Ajax requests, etc.), data processing and presentation to the View (scheduler)

At the heart of vue.js is a system that allows you to declaratively render data into the DOM using a concise template syntax (declarative rendering)

What is the virtual DOM

The Virtual DOM (VIRTUal-DOM) does not operate the DOM immediately, but waits for a series of DOM update operations to complete, inserts it into the HTML at once, and then carries on the subsequent operations to avoid a lot of unnecessary calculation. Therefore, the advantage of using JS objects to simulate DOM nodes is that the update of the page can be reflected in all JS objects (virtual DOM) first, and the speed of operating JS objects in memory is obviously faster. After the update is completed, the final JS objects will be mapped into real DOM, and then submitted to the browser to draw.

Vue1.0 has no virtual DOM, Vue2.0 is based on virtual DOM.

  • Advantages: Reduced DOM operations and improved performance. A. Small, fast traversal! B. Update only the affected elements, high efficiency! C. Encapsulates THE DOM operation, without us programmers to repeat the code!

What is component development

It is an abstraction that allows us to build large applications from small, independent, and often reusable components. The emergence of components is to split the code amount of Vue instance, so that we can divide different functional modules with different components. In the future, we can call the corresponding component for any function we need.

<div id="app">  
    <app-nav></app-nav>  
    <app-view>     
        <app-sidebar></app-sidebar>    
        <app-content></app-content>  
    </app-view> 
</div>
Copy the code
The difference between modularity and componentization
  • Modularity: Divided from the point of view of code logic; Convenient code layered development, to ensure that each functional module of the single function
  • Componentization: partitioned from the perspective of UI interface; Front-end componentization facilitates reuse of UI components
    • reusability

Why do we use Vue

  • Lightweight framework: Focuses only on the view layer, which is a collection of views that build data, only tens of KB in size;
  • Easy to learn: Chinese development, Chinese documents, there is no language barrier, easy to understand and learn;
  • Bidirectional data binding: Retains angular features for easier data manipulation;
  • Componentization: It retains the advantages of React, realizes the encapsulation and reuse of HTML, and has unique advantages in building single-page applications;
  • View, data, structure separation:
    • Making it easier to change data;
    • No logical code changes are required;
    • Only need to operate the data to complete the related operations;
  • Virtual DOM:
    • Dom manipulation is very performance intensive;
    • No more native DOM manipulation nodes;
    • Greatly liberating DOM operations;
    • But it’s the DOM:
      • But in a different way;
  • Run faster:
    • In contrast to React:
      • To operate the virtual DOM:
        • In terms of performance, VUE has a big advantage;

How to use Vue

Vue environment construction

Common plug-ins

  • Webpack: Code modular build packaging tool.
  • Gulp: a flow-based automated build tool.
  • Babel: Write JS using the latest specification.
  • Vue: A progressive framework for building data-driven Web interfaces
  • Express: A fast, open and minimalist Web development framework based on Node.js platform.

All of these packages can be installed using the package management tool NPM.

create a hello world

Import vue.js file in HTML file

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id ="app">
    {{message}}
</div>
Copy the code
// Left el, right data, complete binding
var app = new Vue({
    el: '#app'.data: {message:"Hello Vue!"}})//Hello Vue!
Copy the code

This looks very similar to rendering a string template, but Vue does a lot of work behind the scenes. Now that the data and DOM have been associated, everything is reactive.

System instructions

What is a directive?

Directives are special attributes with a V-prefix. Adds or changes attributes to functionality for HTML

Interpolation {{}}

The most common form of data binding is text interpolation using Mustache syntax (double braces). To add variables to HTML, for example:

<span>Message: {{ msg }}</span>
Copy the code

What can and can’t be put in {{}}

  • You can put: variables, expressions, function calls, creating objects, accessing array elements, triads
  • Cannot put: program structures (branches and loops), function calls with no return value

V-bind — Property binding

V-bind attributes are called directives. Binds data to a specified property,

Writing:

<div v-bind: parameter = "value/expression ></div>Copy the code

. The abbreviation for V-bind is:

V-on — Event listener

To allow users to interact with your application, we can use the V-on (@) directive to add an event listener that calls the methods defined in the Vue instance:

<div id="app-5">
          <p>{{message}}</p>
          <button v-on:click="reverseMessage">Inversion of the message</button>
</div>
Copy the code
          var app5= new Vue({
              el:'#app-5'.data: {message:'Hello Vue.js'
              },
              methods: {reverseMessage:function(){
                      this.message=this.message.split(' ').reverse().join(' ')}}})Copy the code

v-model

v-if — v-show

V-if re-deletes or creates elements each time and has a high switching performance cost

V-show does not re-delete and re-create the DOM each time, but switches the display: None style of the element. High initial render consumption

If the element involves frequent switching, it’s best not to use V-if, but v-show

V-if is recommended if the element may never be shown to the user

v-for

Function: Generate content by traversing the specified template content according to the elements in the array.

<body> <div id="app"> <ul> <! --> <li v-for="item in list">{{item}}</li> </ul> </div> </body> <script> var vm = new Vue({el: '#app', data: { list: [1, 2, 3] } }); </script>Copy the code

// Display the result

  • 1
  • 2
  • 3

v-html

Action: Updates the innerHTML of an element. V-html compiles and displays the HTML content of the bound content

<body>
    <div id="app">
        <p v-html="msg"></p>
    </div>
    <script>
        var vm = new Vue({
            el: '#app'.data: {
                msg: 

'
}})
</script> </body> Copy the code

! Note: Rendering arbitrary HTML dynamically on a web site is very dangerous because it can easily lead to XSS attacks. Use V-HTML only for trusted content, never for user-submitted content.

v-model

Function: Creates a bidirectional binding on a form control or custom component. After binding, the value in the P tag is updated synchronously when the content in the INPUT tag changes.

<input v-model="message" placeholder="edit me">
<p>Message is: {{ message }}</p>
Copy the code

The difference between:

  • V-bind: Implements only one-way data binding and automatically binds data from M to V.
  • V – model: onlyv-modelTo achievetwo-wayData binding.

v-cloak

What it does: This directive maintains the association with the element instance until the associated instance is finished compiling. Often used to solve the problem of the difference expression {{}} flickering.

<style>
  [v-cloak]{
    display:none
  }
  </style>
</head>
<body>
<div id="app">
  <h1 v-cloak> {{name}}</h1>
</div>
<script>
setTimeout(function(){
  var vm=new Vue({
    el:"#app".data: {name:"qianshuSanse"}})},2000)
</script>
</body>/ / 2 s after<h1>The name in the tag is displayedCopy the code

Create a simple commodity quantity manager

<! DOCTYPEhtml>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <title>Document</title>
  </head>

  <body>
    <div id="app">
      <ul>
        <li v-for="product in doubleCount" :key="product.id">
          {{product.name}} -- {{product.count}}
          <span v-show="product.count === 0">Sell didn't pull</span>
          <button @click="product.count++">add</button>
          <input type="text" v-model.number="product.count" />
          double:<span>{{product.double}}</span>
        </li>
      </ul>Total: {{totalCount}}</div>
    <script>
      app = new Vue({
        el: "#app".data: {
          products: [{id: 1.count: 2.name: The word "apple"}, {id: 2.count: 3.name: "Banana"}, {id: 3.count: 5.name: "Peach",}]},computed: {
          totalCount() {
            // js
            return this.products.reduce((total, item) = > {
              return total + item.count;
            }, 0);
          },
          doubleCount() {
            let tempArr = [];
            this.products.forEach((element) = > {
              element["double"] = (element.count - 0) * 2;
            });
            tempArr = this.products;
            returntempArr; ,}}});</script>
  </body>
</html>

Copy the code