Understanding the vue framework

View

Vue is a front-end js framework, developed by You Yuxi, is a personal project currently maintained by the hungry ude team

Vue has received particular attention in recent years. Three years ago, angularJS dominated the front-end JS framework market for a long time, and then the react framework was born, because it has a feature that is a virtual DOM, which crushes angularJS from performance. At this time, Vue 1.0 was quietly released. Its elegance and portability also attracted some users. It began to receive attention. In the middle of 16 years, VUE 2.0 came out. At this time, vue surpassed react in terms of performance and cost. The fire was a complete mess. At this time, the angular development team also developed the angular 2.0 version, and renamed it angular, absorbing the advantages of react and vue, plus the characteristics of angular itself, and also attracted many users.
Learning vue is a must-have skill for front-end developers.

The role of front-end js framework, why use it

The js framework helps developers write js logic code. The functions of js are divided into the following points when developing applications:

  1. Rendering data

  2. Operate dom (write some effects)

  3. Operation cookie and other storage mechanism api

In front-end development, how to efficiently operate DOM and render data is a problem that front-end engineers need to consider, and when the amount of data is large and the flow is chaotic, how to correctly use the data and manipulate the data is also a problem.

The js framework has its own perfect solution to the above problems, reducing development costs, high performance and high efficiency. The only drawback is that it requires a certain cost to learn.

Vue official website introduction

vue is a progressive JavaScript framework. What functions are used, only what functional modules need to be introduced

Insert picture description here

Vue's claim is weak

Vue can be used in any other type of project. The cost of use is lower, more flexible, and weaker. In Vue projects, other technologies can also be easily integrated to develop, and because the Vue ecosystem is particularly large, you can find Basically all types of tools are used in vue projects

Features: easy to use (low cost of use), flexible (complete ecosystem, suitable for projects of any size), high efficiency (small size, good optimization, good performance)

Vue is a MVVM js framework, however, the core library of Vue only focuses on the view layer, and developers only focus on the mapping relationship of mv

Insert picture description here

Introduction and simple use of vue framework

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <div id="test">
         <!-- 声明一条数据,然后用特殊的模板语法将其渲染到界面中 ===> 声明式渲染 -->
        {{msg}}
    </div>

    <!-- 引入vue框架  新手建议引入开发版的vue,有错误代码提示 -->
    <script src="./base/vue.js"></script>
    <script>
        // 创建vue实例
        new Vue ({
            el:"#test",  //el ==> 挂载点
            data:{      //data ==> 数据
                msg:"hello world"
            }     
        })
    </script>
</body>

</html>

MV * mode (MVC / MVP / MVVM)

mv * mode

MVC

Model View Controller

After the user operates the View, the View captures this operation and will transfer the processing power to the Controller; the Controller will preprocess the data from the View and decide which Model interface to call; then the Model will execute the relevant business logic (data Request); When the Model is changed, the View will be notified through the Observer Pattern (Observer Pattern); After receiving the Model Change message through the Observer Mode, the View will request the latest data from the Model and then update the interface again.

把业务逻辑和展示逻辑分离,模块化程度高。但由于View是强依赖特定的 Model的,所以View无法组件化,无法复用

Insert picture description here

MVP

Model View Presenter

Like the MVC mode, the user's operation of the View will be transferred from the View to the Presenter. The Presenter will execute the corresponding application logic and perform the corresponding operations on the Model. At this time, after the Model executes the business logic, it also transmits its changed message through the observer mode, but it is passed to the Presenter instead of the View. After the Presenter obtains the news of the Model change, it updates the interface through the interface provided by the View.

Insert picture description here

View不依赖Model,View可以进行组件化。但Model->View的手动同步逻辑麻烦,维护困难

Example For
Insert picture description here
example, to click the toggle button to make the red box appear hidden, the following is achieved using native js.

<body>  

    <div id="box">
        <button class="btn">toggle</button>
        <button class="btn2">big</button>
        <div class="box">

        </div>
    </div>

    <script>
          //面向过程的代码
        let btnDom = document.querySelector(".btn")
        let boxDom = document.querySelector(".box")
        let flag = true
        btnDom.onclick = function(){
            if(flag){
                boxDom.style.display = "none"
                flag = false
            }else{
                boxDom.style.display = "block"
                flag = true
            }
        } 
    </script>
</body>

If only one function is implemented, it is relatively easy to use native js, but if you need to add multiple functions, this method is undoubtedly the most difficult. If it is replaced with a vue framework, it will be much easier. Let's see how to use the vue framework:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 100px;
            height: 100px;
            background: red;
        }
    </style>
</head>

<body>

    <div id="box">
        <button class="btn">toggle</button>
        <button class="btn2">big</button>
        <div class="box">

        </div>
    </div>

    <!-- 引入vue框架  新手建议引入开发版的vue,有错误代码提示 -->
    <script src="./base/vue.js"></script>
    <script>

        /*
            mvc:
                m:model       数据模型层    dao层 
                v:view        视图层        
                c:controller  控制器       service

            controller的作用:就是将m层的数据在view层进行显示
        
        */

        //   m层
        let model = {
            isShow: true,
            isBig: true
        }

        // v 层
        let boxDom = document.querySelector(".box")

        //c层
        function controller() {
            this.init()
        }
        controller.prototype = {
            init() {
                this.addEvent()
            },
            addEvent() {
                let btnDom = document.querySelector(".btn")
                let btn2Dom = document.querySelector(".btn2")
                // 实现显示隐藏功能
                btnDom.onclick = () => {
                    // 更改数据
                    model.isShow = !model.isShow
                    // 渲染视图
                    this.render()
                }
                // 添加放大 还原功能
                btn2Dom.onclick = () => {
                    // 更改数据
                    model.isBig = !model.isBig
                    // 渲染视图
                    this.render()
                }
            },
            // 要实现的效果
            render() {
                boxDom.style.display = model.isShow ? "block" : "none"
                boxDom.style.width = model.isBig ? "300px" : "100px"
            }
        }

        new controller()

    </script>
</body>
</html>

In this way, it is much easier.
Insert picture description here

MVVM

Model View ViewModel

The calling relationship of MVVM is the same as MVP. However, there will be something called Binder or Data-binding engine in the ViewModel. You only need to imperatively declare in the view's template syntax which part of the model the data displayed on the view is bound to. When the ViewModel updates the Model, Binder will automatically update the data to the View; when the user operates the View (such as form input), Binder will automatically update the data to the Model. This method is called: Two-way data-binding, two-way data binding .

It uses two-way binding (data-binding): View changes are automatically reflected in the ViewModel, and vice versa

Insert picture description here

Use of Vue

Vue does not support IE8 because many features of ES5 are used
Object.defineProperty (_data, "msg", {get (), set ()}) _data.msg

  • Vue.js can be introduced directly through the script tag. There are development version and production version. The development version is generally introduced when we develop the project. When the final development is completed, the production version is introduced. The development version is not compressed, and there are many tips , And the production version is deleted

Download and use directly

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  • A scaffold (command line tool) is provided in Vue to help us quickly build a webpack-based development environment ...
npm install ‐g @vue/cli

Examples of Vue

Each application has a root instance. In the root instance, we implement large applications by nesting components

In other words, components are not necessarily required, but examples are required

When instantiating an instance, we can pass in one; configuration items, setting many attribute methods in the configuration items can achieve complex functions

The el property can be set in the configuration. The el property represents the scope of this instance

Set the data property in the configuration to bind data to the instance

Principle of vue's two-way data binding

  • When you pass a normal JavaScript object into a Vue instance as a data option, Vue will traverse all the properties of this object and use Object.defineProperty to convert all these properties to getter / setter. Object.defineProperty
    is a feature that cannot be simulated in ES5, which is why Vue does not support IE8 and earlier browsers. Each component instance corresponds to a watcher instance, which records the "touched" data attributes as dependencies during component rendering. Then when the setter of the dependency is triggered, the watcher will be notified, so that its associated components are re-rendered.

  • When vue creates a vm, it will configure the data into the instance, and then use the Object.defineProperty method to dynamically add getter and setter methods for the data. When getting data, the corresponding getter method is triggered, and when setting the data, the corresponding setter method is triggered. Then when the setter method triggers completion, the watcher will be further triggered internally. When the data changes, the view update operation is completed.

Vue internally implements two-way data binding through data hijacking & publish-subscribe model

  • Through the Object.defineProperty method to hijack all data, is to dynamically add getter and setter methods to these data. When the data changes, it publishes a message to the subscriber (Watcher), triggering the response monitoring callback.

Insert picture description here

<body>
    
    <div id="app">
       
    </div>


    <script src="./base/vue.min.js"></script>
    <script>
    
        var obj = {}
        let middel = 100
        Object.defineProperty(obj,"msg",{
            get(){
                return middel
            },
            set(val){
                middel = val
            }
        })

        console.log(obj.msg)   //获取对象的属性的时候,会调用自身的get方法
        obj.msg = 1111           //设置对象的属性的时候,会调用自身的set方法
        console.log(obj.msg)     
    </script>
</body>

Extension:

Note: The change of vue3 Object.defineProperty has the following disadvantages.

1. Unable to monitor es6 Set and Map changes;

2. Unable to monitor the data of Class type;

3. New or deleted attributes cannot be monitored;

4. The addition and deletion of array elements cannot be monitored.

For the shortcomings of Object.defineProperty, ES6 Proxy can be perfectly solved. Its only shortcoming is that it is not friendly to IE, so vue3 detects that if it is using IE (yes, IE11 does not support Proxy), it will Automatically downgrade to the data monitoring system of Object.defineProperty.

Published 31 original articles · Likes4 · Visits 1005

Guess you like

Origin blog.csdn.net/qq_43942185/article/details/104952571