Hello, I’m front arashi maple, a second-tier cities program are gentle, the second half of the year is special for us a few months, at the end of July, zhengzhou in the worst floods in many years, can not travel, rest at home, in August the outbreak, the home office for a month, September outbreaks in the past, finally to company work. The blog has also been neglected for a period of time. In the future, I will update some vUe-related articles one after another to make progress together with my family

Vue Core Concepts and Features (I)

Vue (pronounced vju/curliest, similar to View) is a set of progressive frameworks for building user interfaces. Features: Easy to use, flexible, efficient progressive framework

Vue + Components + VUe-Router + vuex + VUE-CLI can be randomly combined

I. Concept and features of Vue

1. What is a library and what is a framework?

  • A library is a collection of code into a product, a library is we call the methods in the library to implement their own functions.
  • A framework is a product developed to solve a class of problems. A framework is the code we write in a specific place and the framework calls it for us.

The most fundamental difference between frameworks and libraries is control: You call libs, frameworks call You

Vue belongs to the framework

2.MVC model && MVVM model

  1. M: Model: data in corresponding data
  2. V: View: template
  3. VM: ViewModel: Vue instance object

In traditional MVC, all logic except model and View is placed in controller, which makes controller logic complex and difficult to maintain. In MVVM, there is no direct relationship between View and Model, and all interactions are carried out through viewModel

Vue is MVVM mode

3. Declarative and imperative

  • Writing a for loop yourself is imperative (telling it to get the result in its own way)
  • Declarative is using the array method forEach (we want a loop, inside to do it for us)

Ii. Basic use of Vue

1. The mustache syntax

Allows developers to declaratively bind DOM to the data of the underlying Vue instance. Data needs to be declared before being used

  • Writing a ternary expression
  • Get the return value
  • JavaScript expression
<div id="app">
    {{ 1+1 }}
    {{ msg == 'hello'?'yes':'no'}} {{{name:1} }}
</div>
<script src="./node_modules/vue/dist/vue.js"></script>
<script>
let vm = new Vue({
    el:'#app'.data: {msg:'hello'}})</script>
Copy the code

2. Responsive data change

Object. DefineProperty is used in Vue to redefine attributes in objects, or override methods on array prototypes if they are arrays

function notify() {
    console.log('View Update')}let data = {
    name: 'jw'.age: 18.arr: [1.2.3]}// Override the array method
let oldProtoMehtods = Array.prototype;
let proto = Object.create(oldProtoMehtods);
['push'.'pop'.'shift'.'unshift'].forEach(method= > {
    proto[method] = function (. args) {
        let inserted;
        switch (method) {
            case 'push':
            case 'unshift':
                inserted = args;
                break;
        }
        observerArray(inserted)
        notify();
        oldProtoMehtods[method].call(this. args) } })function observerArray(obj) { // Observe each item in the array
    for (let i = 0; i < obj.length; i++) { observer(obj[i]); }}function observer(obj) {
    if(typeofobj ! = ='object') {return obj
    }
    if (Array.isArray(obj)) {
        obj.__proto__ = proto
        observerArray(obj);
    }else{
        for (let key inobj) { defineReactive(obj, key, obj[key]); }}}function defineReactive(obj, key, value) {
    observer(value); // Loop value again
    Object.defineProperty(obj, key, { // Arrays are not supported
        get() {
            return value;
        },
        set(val){ notify(); observer(val); value = val; }}); } observer(data); data.arr.push({name:'jw'})
console.log(data.arr);
Copy the code

defects

  • You cannot change an array by length or index
  • Cannot add new attributes to an object
  • Need to pass throughvm.$setandvm.$deleteMethod to force reactive data to be added/removed

Features: When you use an object, you must first declare a property, which is reactive

  • Views cannot be updated by adding nonexistent attributes (vm.$set)
  • Getters and setters are added recursively by default
  • Objects in arrays are responsive and have no effect if they are constant
  • Changing the array index and length does not cause the view to update
  • If new data is added, vUE will also help you monitor (object type).

3. Methods on Vue instances

  • vm.$el;
  • vm.$data;
  • vm.$options;
  • vm.$nextTick();
  • vm.$mount();
  • vm.$watch();
  • vm.$set();
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <meta HTTP-equiv =" x-UA-compatible "content=" IE =edge"> <title>Document</title> </head> <body> <div id="app">{{name}} {{age.age}}</div> <script src="node_modules/vue/dist/vue.js"></script> <script> let vm = new Vue({ el:'#app', data(){ return {name:'zf',age:{}} } }); (promie. Then MutationObserver setimmediate SetTimeout) {// 1) Vue does not rerender the DOM during this loop $watch("name",function (newValue,oldValue) {console.log(newValue,' after '); $watch("name",function (newValue,oldValue) {console.log(newValue,' after '); }); // vm.name = 'jw'; // vm.name = 'zf1'; $nextTick(()=>{console.log(vm.$el.innerhtml); // Render real dom}); Console. log(' VM data ',vm.$data); // Console. log(' options in vm ',vm.$options) for the current instance; // vm.age = 100; // vm.age = 100; // vm.age = 100; vm.$set(vm.age,'age',100); / / Object. DefineProperty / / vm. $set ([1, 2, 3], '0', 100); // vm.$el // vm.$options // vm.$watch // vm.$nextTick // vm.$set </script> </body> </html>Copy the code

Instructions in Vue

Directives in VUE are special Directives with a V-prefix, and their primary function is to manipulate the DOM

1.v-once

<div v-once>{{state.count}} </div>
Copy the code

2.v-html

Never use V-HTML for user input, it can lead to XSS attacks

<div v-html="text"></div>
Copy the code

3.v-bind

Dynamically bound properties need to be bound using V-bind

<img v-bind:src="src">
Copy the code

You can use: to short v-bind

4.v-for

<template v-for="(fruit,index) in fruits" >
    <li :key="`item_${index}`">{{fruit}}</li>
    <li :key="`fruit_${index}`">{{fruit}}</li>
</template>
Copy the code

If multiple elements are looping, the template tag should be added to the outer layer, and the key should be added to the real element. The key should not be repeated, and the index should not be used as the key value

Here’s an example of a key value:

5.v-if/v-else/v-show

V-show can toggle whether or not a DOM element exists, and internal instructions will not be executed when v-if is false. V-show can control the display and hiding of elements, mainly controlling the element style

6.v-on

  • Event binding V-on Binding event
  • Event modifier (.stop.prevent).capture. Self. Once

7.v-model

Two-way data binding

<input type="text" :value="value" @input="input">
<input type="text" v-model="value">
Copy the code
  • select
<select v-model="select">
    <option 
        v-for="fruit in fruits"
        :value="fruit">
            {{fruit}}
    </option>
</select>
Copy the code
  • radio
 <input type="radio" v-model="value"  value="Male">
 <input type="radio" v-model="value"  value="Female">
Copy the code
  • checkbox
<input type="checkbox" v-model="checks" value="Swimming" >
<input type="checkbox" v-model="checks" value="Fitness">
Copy the code
  • The.number.lazy. Trim modifier applies
<input type="text" v-model.number="value">
<input type="text" v-model.trim="value">
Copy the code
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <meta HTTP-equiv =" x-UA-compatible "content=" IE =edge"> <title>Document</title> </head> <body> <div id="app"> <! - {{}} moustache syntax can operation values (calculated to return results) do three expression - > {{name}} {{1 + 1}} {{[1, 2, 3]}} {{true? 'is' : null}} <! - take the object must be separated by Spaces - > {{{name: '123'}}} < span v - once > a {{name}} < / span > <! -- Do not display user input on the page XSS attack --> <! <span v-html=" TMP "></span> <! <div v-bind:title="name"> Hello </div> <! <div :title="name"> Hello </div> <! -- V-for loop data array object number (string) --> <! Write v-for to whoever you want to loop --> <! What does the key in vue do to distinguish elements if I have a button to reverse order --> <! -- Static demonstration that you can use this index to distinguish elements with unique keys --> <! <div v-if="false"> <template v-for="(fruit,index) in arr" > <li :key=" 'name_${index}' >  {{fruit.name}} </li> <li :key="`color_${index}`"> {{fruit.color}} </li> </template> </div> <! -- v-show (show style) --> <! The function of the directive is to encapsulate dom manipulation --> <! -- V-for and V-if do not use together --> <! -- v-show cannot be used with template --> <! <template v-if="isShow"> <span> hello </span> <input type="text" key="1"> </template> <template Bad v - else > < span > < / span > < input type = "text" key = "2" > < / template > <! -- Bidirectional binding as long as the component can be changed bidirectional binding --> <br> <! -- How to bind methods v-on is the full spelling of @ --> <! - $event refer to the event source - > < input type = "text" : value = "value" @ input = "fn ($event)" > <! - long - > < input type = "text" : value = "value" @ input = "e = > value = e. arget. Value" > <! <input type="text" v-model="value"> {{value}} </div> <! <script SRC ="node_modules/vue/dist/vue.js"></script> <script> let vm = new Vue({ el: Fn (e){// this means window this.value = e.target.value}}, Data () {return {value:' hello ', isShow:true, TMP :'<h1> I am handsome </h1>', name: 'zf, arr: [{name:' orange 'color: "green"}, {name: "banana", color:' yellow '}]}}}); </script> </body> </html>Copy the code

4. Custom instruction

  • Global and local directives
  • Write a custom directive
    • The hook functions bind, inserted, update
    <input type="text" v-focus.color="'red'">
    Vue.directive('focus', {inserted:(el,bindings) = >{
            let color = bindings.modifiers.color;
            if(color){
                el.style.boxShadow = `1px 1px 2px ${bindings.value}`} el.focus(); }});Copy the code
  • Clickoutside instruction
    <div v-click-outside="change">
        <input type="text"  @focus="flag=true" >
        <div v-show="flag">
            contenter
        </div>
    </div>
    <script>
        let vm = new Vue({
            el:'#app'.data: {flag:false
            },
            methods: {change(){
                    this.flag = false}},directives: {'click-outside'(el,bindings,vnode){
                    document.addEventListener('click'.(e) = >{
                        if(! el.contains(e.target,vnode)){let eventName = bindings.expression;
                            vnode.context[eventName]()
                        }
                    })
                }
            }
        })
    </script>
Copy the code

Life cycle in Vue

  • BeforeCreate is called after instance initialization and before data Observer and Event/Watcher event configuration.
  • Called after the created instance has been created. In this step, the instance completes the configuration of data Observer, property and method operations, and Watch/Event event callbacks. There’s no $el here
  • BeforeMount is called before the mount begins: the associated render function is called for the first time.
  • Mounted el is replaced by a newly created vm.$el.
  • BeforeUpdate is called when data is updated and occurs before the virtual DOM is re-rendered and patched.
  • Updated This hook is called after the virtual DOM is re-rendered and patched due to data changes.
  • BeforeDestroy Called before instance destruction. At this step, the instance is still fully available.
  • Called after the Destroyed Vue instance is destroyed. When called, everything indicated by the Vue instance is unbound, all event listeners are removed, and all subinstances are destroyed. This hook is not called during server-side rendering.

What to do in a hook function

  • A Created instance has been created because it is the first trigger to make requests for data and resources.
  • The Mounted instance is mounted. DOM operations can be performed on it
  • BeforeUpdate can further change the state in this hook without triggering additional rerendering.
  • Updated performs DOM-dependent operations. In most cases, however, you should avoid changing the state during this period, as this can lead to an infinite update loop. This hook is not called during server-side rendering.
  • Destroyed performs optimization operations, clears timers, and unbinds events

6. Interview questions

  • Please explain your understanding of MVVM
  • Vue realizes the principle of data bidirectional binding
  • What are the common instructions for Vue?
  • V – the principle of the model
  • V-if is different from V-show
  • The function of the key value in Vue