Hello, everyone, I am Front-end LAN Feng, a program yuan in a second-tier city, the last part mainly shared with the “Vue core concepts and features (1)”, today mainly share with you some common Vue core applications I sorted out, It mainly includes some form components, custom commands, modifiers, watch, computed, animation, the life cycle of VUE and some commonly used interview questions. I will share the answers to the vUE interview questions in the future.

I. Use of V-Model

1.1 select

<select v-model="select">
    <option 
        v-for="fruit in fruits"
        :value="fruit">
            {{fruit}}
    </option>
</select>
Copy the code

1.2 radio

 <input type="radio" v-model="value"  value="Male">
 <input type="radio" v-model="value"  value="Female">
Copy the code

1.3 the checkbox

<input type="checkbox" v-model="checks" value="Swimming" >
<input type="checkbox" v-model="checks" value="Fitness">
Copy the code

1.4 Apply.number.lazy. Trim

<input type="text" v-model.number="value">
<input type="text" v-model.trim="value">
Copy the code

2. 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

3. Watch and computed

Why is there always an interview asking the difference between them? Both Watch and computed internally invoke New Watcher

3.1 Watch (Monitoring)

Let’s start with watch

let vm = new Vue({
    el: '#app'.data: { name: 'zf'}});function initWatch(key,handler){
    vm.$watch(key,handler);
}
initWatch('name'.function(newValue){
    console.log(newValue)
});
vm.name = 'jw'; // Data changes are executed by the corresponding handler
Copy the code

When the data changes, the corresponding processing function will be executed

3.2.com puted

let dirty = true; // There is an internal dirty value detection system
function initComputed(key,handler) {
    Object.defineProperty(vm, key, {
        get() {
            if (dirty) { // Change dirty to false
                value = handler();
                dirty = false;
            }
            return value
        }
    })
}
initComputed('age'.function () {
    console.log('Value once')
    return vm.name
});
console.log(vm.age);
console.log(vm.age);
vm.name = 'hello'; // When the dependency value changes, dirty is changed to true to ensure that the latest value is obtained
dirty = true;
console.log(vm.age);
Copy the code

Through the source code, Watcher to achieve dirty value detection

function initComputed(key,handler) {
        // The source code dirty is through watcher to automatically update the value of dirty
    let watcher = new Watcher(vm,handler,function(){}, {lazy:true});
    Object.defineProperty(vm, key, {
        get() {
            if (watcher.dirty) { // Change dirty to false
                value = handler();
                watcher.dirty = false;
            }
            return value
        }
    });
}
Copy the code
  • Watch executes the corresponding callback every time the value changes
  • Computed property multiple values are computed using caching effects that are reperformed if dependent values change
  • computed defineProperty get / set

4. The animation

Elements can be shown and hidden to add animation effects V-if, V-show, V-for, route switching and other operations.

Common ways to add animations are animation, Transition, and JS

4.1 range of animation

Let’s start by understanding the trigger phase of each style

<div @click="show()">Show/Hide</div>
<transition>
    <div class="content" v-if="isShow"></div>
</transition>
Copy the code
.content{
    width: 100px;height: 100px;background: red;;;
}
.v-enter{ /* Before entering */
    background: blue;
    opacity: 0;
}
.v-enter-active{ /* Enter the middle */
    transition: all 2s linear;
}
.v-enter-to{ / * * / target
    background: black;
}
/* Return to the default red */
.v-leave{ /* Start to leave */
    background: yellow;
}
.v-leave-active{ /* Leave the middle */
    transition: all 2s linear;
}
.v-leave-to{ / * * / target
    background: green;
}
/* Element hidden */
Copy the code

We can use the name attribute to change the default V – prefix

Use with **animate. CSS **

Install the animate. CSS

npm install animate.css
Copy the code
<link rel="stylesheet" href="node_modules/animate.css/animate.css">
<style >
    .content{
        background: red;width: 100px;height: 100px;
    }
    .v-enter-active{
        animation:bounceIn 1s ease-in;
    }
    .v-leave-active{
        animation:bounceOut 1s ease-in ;
    }
</style>
Copy the code

You can also specify styles directly

<transition enter-active-class="bounceIn" leave-active-class="bounceOut">
    <div class="content animated" v-if="isShow"></div>
</transition>
Copy the code

4.2 Write animation with JS

Common hooks

  • Before-enter Indicates before the Enter is triggered
  • Before-leave Indicates before the leave is triggered
  • Enter Enters the animation process
  • Leave Leaves the animation process
  • After-enter Enters the end of the animation
  • The after-leave animation ends

Example of adding a shopping cart:

<ul>
    <li v-for="(list,index) in lists" ref="lists">
        <div class="cover">
            <img :src="list.cover">
        </div>
        <button @click="addCart(index)">Add to shopping cart</button>
    </li>
    <! -- Implement animation -->
    <transition @enter="enter" @after-enter="afterEnter" >
        <span class="animate" v-if="showAnimate"></span>
    </transition>
</ul>
<div class="cart" ref="cart">Come in!!!!!!</div>
Copy the code

We can use v-if for animation

let vm = new Vue({
    el: '#app'.methods: {enter(el,done){ // This function is triggered on entry
            // Assign the background image of the currently clicked item to the animation element
            el.style.background = `url(The ${this.lists[this.currentIndex].cover}) `;
            // Set the element background
            el.style.backgroundSize = ` ` 100% 100%;
            // Put the animation element in the specified position
            let {x,y} = this.$refs.lists[this.currentIndex].getBoundingClientRect();
            el.style.left = x +'px';
            el.style.top = y + 'px';
            el.style.transformOrigin = `center center`;

            // Get the animation target position
            let {x:a,y:b} = this.$refs.cart.getBoundingClientRect();
            el.style.transform = `translate3d(${a-x}px,${b-y}` px, 0) scale (0, 0);
            el.addEventListener('transitionend',done); // Trigger the done method after the animation ends
        },
        afterEnter(){ // Reset the animation when finished
            this.showAnimate = false; // Hide it directly
        },
        addCart(index){
            // Add to cart
            this.currentIndex = index; // The item currently clicked
            this.showAnimate = true; }},data() {
        return {
            showAnimate:false.currentIndex: -1.lists: [{
                    cover: 'http://www.javascriptpeixun.cn/files/course/2019/10-13/20510264fa40871768.png'.id: 1}, {cover: 'http://www.javascriptpeixun.cn/files/course/2019/10-13/21114956089d654633.png'.id: 2}, {cover:'http://www.javascriptpeixun.cn/files/course/2019/10-13/2048331a9c5a183234.png'.id:3,}]}}})Copy the code

4.3 Multi-element animation

Transition-group is used if the animation encounters v-for, and each element must add a key attribute

<div class="nav-list" ref="box">
    <transition-group>
        <div class="nav-item" v-for="i in count" v-show="isShow" :key="i">{{i}}</div>
    </transition-group>
</div>
<div class="nav" @click="show()">navigation</div>
<script>
    let vm = new Vue({
        el: '#app'.methods: {// Control whether to display
            show(){this.isShow = !this.isShow}
        },
        data() {
            return {
                isShow: false.count:6 // Loop through six navigations}}})</script>
Copy the code
.nav-list .v-enter{ /* Enter the state */
    opacity: 0;
    transform: translate(0.0);
}
.v-enter-active..v-leave-active{ /* Effect in motion */
    transition: all .5s linear;
} 
.nav-list .v-leave-to{ /* The goal after leaving */
    transform: translate(0.0);
    opacity: 0;
}
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

  • What is the difference between computed and Watch?
  • The life cycle of Vue, and the specific scenarios for each life cycle
  • What is ref in Vue?
  • Vue animation life cycle?
  • How does Vue write custom instructions?