Writing in the front

Believe in friends all have certain knowledge of vue or use, after all, now the front one of the most popular framework, vue is one of the most studious and entry is relatively simple, after all is in Chinese, kindness, and I, now work with the main framework is also a vue, likes traced back, recently around or to do a lot of friend to interview the interviewer, Feedback of such and such big guy, write code bang, but in the principle and use scenarios is not enough thorough, so here is to summarize some of you usually do not pay attention to the point, from VUE entry to the source code small implementation, write to communicate with you.

Starting from 0

What is a vue?

Vue (pronounced /u: /, similar to VEw) is a set of progressive frameworks for building user interfaces. Features: Easy to use, flexible, efficient progressive framework; Increment vUE + Components + vue-Router +vuex+vue-cli one by one

What is a library and what is a framework?

A library is a collection of code into a product. A library is where we call the methods in the library to implement our own functionality. (For example, jquery is a library.) A framework is a product that is developed to solve a problem where we write the code and the framework calls it for us. (Vue, React, NG) All in all, the framework is an updated version plus of the library.

/ /... Import library etc.let vm = new Vue({
            el:'#app',
            //template: '<h1>hello world</h1>', data:{// store data MSG:'hello',
                info:{xxx:'xxx'}, arr: [1, 2, 3, 4]}}); vm.$nextTick(()=>{
            console.log(vm.$el.innerHTML); 
            console.log(vm.$options); 
        });
        vm.$watch('info.xxx'.function(newValue,oldValue){
            console.log(newValue,oldValue);
        })
Copy the code

Method VM on the vue instance.The options nextTick etc.

Of course you can print on the console

mvvm

In traditional MVC, all logic except mode and VEW is placed in controller, which leads to complex controller logic and difficult to maintain. In MWM, THERE is no direct relationship between VEW and mode, and they all interact through vIewMode

Convenient for you to deepen the impression of baidu a picture:

Template syntax

Allows developers to declaratively bind the DOM to the data of the underlying VUE instance. Before you can use the data, you need to declare that you are writing ternary expressions JavaScript expressions

<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="app"> <! - values expression can operation, the values for three yuan - > {{1 + 1}} {{MSG}} {{flag?'ok':'no'}}
        {{ {name:1} }}
        {{ 'msg' + 'hello'}}
    </div>
    <script src="node_modules/vue/dist/vue.js"></script>
    <script>
        let vm = new Vue({
            el:'#app',
            data:{
                msg:'hello',
                flag:true}}); </script> </body> </html>Copy the code

Highlight – – Observe changes in data

Vue data hijacking, you must know object.defineProperty, the following code is simple implementation

/ / the data sourcelet obj = {
    name:'jw',
    age: {
        age:18
    }
}
function observer(obj){
    if(typeof obj == 'object') {for(let key inobj){ defineReactive(obj,key,obj[key]); }}}functiondefineReactive(obj,key,value){ observer(value); Object.defineproperty (obj,key,{object.defineProperty (obj,key,{get() {return value
        },
        set(val){ observer(val); // If the value is set to an object you need to monitor this object console.log('Data updated')
            value = val;
        }
    })
}
observer(obj);
obj.age = {name:1};
Copy the code

Object. DefienProperty does not support an array.

// Vue overrides all methods on the arraylet arr = ['push'.'slice'.'shifit'.'unshift']
arr.forEach(method=>{
    let oldPush = Array.prototype[method];
    Array.prototype[method] = function(value){
        console.log('Data updated')
        oldPush.call(this,value);
    }
})

obj.age.push(5);
obj.age.length--;
Copy the code

The view is not refreshed if the property does not exist by default

The array call push is invalid

V – vue instructions

In VUE Directives, these are special features prefixed with V-directives. The main function is to operate the DOM. The code describes the Directives

<div id="app"> <! <div v-once>{{MSG}}</div> <! XSS attacks cannot display the user's input. The content must be trusted"d"></div> <! -- if it doesn't work, the dom will disappear --> <! -- v-if controls dom -- v-show controls style --> <! -- v-show does not support template --> <template v-show="flag">
           <div>hello</div>
           <div >123</div>
       </template>
      <div>312</div>
   </div>
Copy the code

We’ll talk about this later in the Diff algorithm, but the key can be used to distinguish between elements, so try not to use index as a key if you have a unique identifier, use a unique identifier if you have a unique identifier. One thing you need to be careful about is that when you do a template loop, you put the key on the child element. Vue 2.5 requires the use of the key attribute when looping.

 <template v-for="i in 3" >
   <div :key="i+'_1'" :a="i+'_1'">{{i}}</div>
   <div :key="`${i}_2 `" :a="`${i}_2 `" a="{{i}}">{{i}}</div>
</template>
Copy the code

V-model implementation of an input box bidirectional binding only needs

<input type="text" v-model="msg">
Copy the code

Actually, v-model is a syntactic sugar for @input + :value

<input type="text" :value="msg" @input="e=>msg=e.target.value">
Copy the code

Computed attribute computed

Small interview questions:

The difference between computed and Method

  • For computed, the cache is available, but for method, it is not

Computed and watch are different

  • Watch supports asynchrony
  • Watch can implement some simple functions. First think about computed
<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="app">
        {{ fullName }} 
        {{msg}}
    </div>
    <script src="./node_modules/vue/dist/vue.js"></script>
    <script>
         let vm = new Vue({
             el:'#app',
             data:{
                 firstName:'big',
                 lastName:'fly',
                 msg:'hello',
                 fullName:' '
             },
            //  mounted(){// By the way, the hook function is called at different stages // this.getFullName(); // }, methods:{getFullName(){
                    this.fullName = this.firstName + this.lastName
                }
             },
             watch:{ // vm.$watch('firstname',()=>{})
                firstName:{
                    handler(newValue){
                        setTimeout(()=>{
                            this.getFullName();
                        },1000)
                    },
                    immediate:true // deep:true
                },
                lastName(){ this.getFullName(); }}, computed:{// object.definePropertyfullName(){// The get method, which has a cache, will take the value from the cache if the value has not changedreturn this.firstName + this.lastName
                }
             },
            //  methods:{
            //      getFullName(){
            //          console.log('ha ha') / /return this.firstName + this.lastName
            //      }
            //  }
         })
    </script>
</body>
</html>
Copy the code

Computed, I’m going to go a little bit deeper, and I’m sure you’re going to do multiple checkboxes, but you’re probably going to use methods, so try computed, it’s a little bit less code and a little bit more elegant.

<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="app"> all < inputtype="checkbox" v-model="checkAll">

        <input type="checkbox" v-for="(item,key) in checks" v-model="item.value" :key="key">

    </div>
    <script src="./node_modules/vue/dist/vue.js"></script>
    <script>
         let vm = new Vue({
             el:'#app',
             data:{
                 checks:[{value:true},{value:false},{value:true}],
             },
             computed:{
                 checkAll:{
                     get() {return this.checks.every(check=>check.value)
                     },
                     set(value){this.checks. ForEach (check =>check.value = value); } } } }) </script> </body> </html>Copy the code

I will write here tonight, and I will continue to update custom instructions, life cycle, Router, vuEX, and after the basic pit point, we will look at their simple implementation of the small principle. Thank you for being here. See you!