search
HomeWeb Front-endJS TutorialDetailed explanation of MVVM principles and implementation methods in Vue

Detailed explanation of MVVM principles and implementation methods in Vue

Analysis and implementation of MVVM principles in Vue

First of all, you need to have a certain understanding of Vue Understand, know MVVM. This will help you to successfully complete the reading, learning and writing of the following principles

The following is a detailed walkthrough of the MVVM principles in Vue by my Aba Aba For the implementation, you can learn from this article:

1. Vue data two-way binding core code module and implementation principle

2. How does the subscriber-publisher pattern allow data to drive the view, the view to drive the data, and then the view to drive the view

3. How to parse the instructions on the element node and associate the subscriber to implement the view Update

1. Organize ideas

##Flow chart of implementation:

Detailed explanation of MVVM principles and implementation methods in Vue

If we want to implement a simple version of the Vue framework similar to MVVM, we need to implement the following points:

1. Implement a data monitoring Observer to monitor all properties of the data object. If the data changes, the latest value can be obtained to notify subscribers.

2. Implement a parser, Compile, to parse the page node instructions and initialize the view.

3. Implement an observer Watcher, subscribe to data changes and bind related update functions. And put yourself into the observer collection Dep. Dep is the bridge between Observer and Watcher. Data changes are notified to Dep, and then Dep notifies the corresponding Watcher to update the view.

2. Implementation

The following is written in ES6, which is relatively concise, so it can be implemented in more than 300 lines of code. A simple MVVM framework.

1. Implement the html page

Define some data and instructions on the page according to Vue’s writing method, and introduce two JS document. First instantiate an MVue object and pass in our el, data, and methods parameters. Let’s look at it later. What is the Mvue.js file?

html

<body>
  <div id="app">
    <h2 id="person-name-nbsp-nbsp-person-age">{{person.name}} --- {{person.age}}</h2>
    <h3 id="person-fav">{{person.fav}}</h3>
    <h3 id="person-a-b">{{person.a.b}}</h3>
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
    </ul>
    <h3 id="msg">{{msg}}</h3>
    <div v-text="msg"></div>
    <div v-text="person.fav"></div>
    <div v-html="htmlStr"></div>
    <input type="text" v-model="msg">
    <button v-on:click="click111">按钮on</button>
    <button @click="click111">按钮@</button>
  </div>
  <script src="./MVue.js"></script>
  <script src="./Observer.js"></script>
  <script>
    let vm = new MVue({
      el: &#39;#app&#39;,
      data: {
        person: {
          name: &#39;星哥&#39;,
          age: 18,
          fav: &#39;姑娘&#39;,
          a: {
            b: &#39;787878&#39;
          }
        },
        msg: &#39;学习MVVM实现原理&#39;,
        htmlStr: &#39;<h4 id="大家学的怎么样">大家学的怎么样</h4>&#39;,
      },
      methods: {
        click111() {
          console.log(this)
          this.person.name = &#39;学习MVVM&#39;
          // this.$data.person.name = &#39;学习MVVM&#39;
        }
      }
    })
  </script>

</body>

2. Implement parser and observer

MVue .js

// 先创建一个MVue类,它是一个入口
Class MVue {
    construction(options) {
        this.$el = options.el
        this.$data = options.data
        this.$options = options
    }
    if(this.$el) {
        // 1.实现一个数据的观察者     --先看解析器,再看Obeserver
        new Observer(this.$data)
        // 2.实现一个指令解析器
        new Compile(this.$el,this)
    }
}
?
// 定义一个Compile类解析元素节点和指令
class Compile {
    constructor(el,vm) {
        // 判断el是否是元素节点对象,不是就通过DOM获取
        this.el = this.isElementNode(el) ? el : document.querySelector(el)
        this.vm = vm
        // 1.获取文档碎片对象,放入内存中可以减少页面的回流和重绘
        const fragment = this.node2Fragment(this.el)

        // 2.编辑模板
        this.compile(fragment)

        // 3.追加子元素到根元素(还原页面)
        this.el.appendChild(fragment)
    }

    // 将元素插入到文档碎片中
    node2Fragment(el) {
        const f = document.createDocumnetFragment();
        let firstChild
        while(firstChild = el.firstChild) {
            // appendChild
            // 将已经存在的节点再次插入,那么原来位置的节点自动删除,并在新的位置重新插入。
            f.appendChild(firstChild)
        }
        // 此处执行完,页面已经没有元素节点了
        return f
    }

    // 解析模板
    compile(frafment) {
        // 1.获取子节点
        conts childNodes = fragment.childNodes;
        [...childNodes].forEach(child => {
            if(this.isElementNode(child)) {
                // 是元素节点
                // 编译元素节点
                this.compileElement(child)
            } else {
                // 文本节点
                // 编译文本节点
                this.compileText(child)
            }

            // 嵌套子节点进行遍历解析
            if(child.childNodes && child.childNodes.length) {
                this.compule(child)
            }
        })
    }

    // 判断是元素节点还是属性节点
    isElementNode(node) {
        // nodeType属性返回 以数字值返回指定节点的节点类型。1-元素节点 2-属性节点
        return node.nodeType === 1
    }

    // 编译元素节点
    compileElement(node) {
        // 获得元素属性集合
        const attributes = node.attributes
        [...attributes].forEach(attr => {
            const {name, value} = attr
            if(this.isDirective(name)) { // 判断属性是不是以v-开头的指令
                // 解析指令(v-mode v-text v-on:click 等...)
                const [, dirctive] = name.split('-')
                const [dirName, eventName] = dirctive.split(':')
                // 初始化视图 将数据渲染到视图上
                compileUtil[dirName](node, value, this.vm, eventName)

                // 删除有指令的标签上的属性
                node.removeAttribute('v-' + dirctive)
            } else if (this.isEventName(name)) { //判断属性是不是以@开头的指令
                // 解析指令
                let [, eventName] = name.split('@')
                compileUtil['on'](node,val,this.vm, eventName)

                // 删除有指令的标签上的属性
                node.removeAttribute('@' + eventName)
            } else if(this.isBindName(name)) { //判断属性是不是以:开头的指令
                // 解析指令
                let [, attrName] = name.split(':')
                compileUtil['bind'](node,val,this.vm, attrName)

                // 删除有指令的标签上的属性
                node.removeAttribute(':' + attrName)
            }
        })
    }

    // 编译文本节点
    compileText(node) {
        const content = node.textContent
        if(/\{\{(.+?)\}\}/.test(content)) {
            compileUtil['text'](node, content, this.vm)
        }
    }

    // 判断属性是不是指令
    isDirective(attrName) {
        return attrName.startsWith('v-')
    }
    // 判断属性是不是以@开头的事件指令
    isEventName(attrName) {
        return attrName.startsWith('@')
    }
    // 判断属性是不是以:开头的事件指令
    isBindName(attrName) {
        return attrName.startsWith(':')
    }
}
?
?
// 定义一个对象,针对不同指令执行不同操作
const compileUtil = {
    // 解析参数(包含嵌套参数解析),获取其对应的值
    getVal(expre, vm) {
        return expre.split('.').reduce((data, currentVal) => {
            return data[currentVal]
        }, vm.$data)
    },
    // 获取当前节点内参数对应的值
    getgetContentVal(expre,vm) {
        return expre.replace(/\{\{(.+?)\}\}/g, (...arges) => {
            return this.getVal(arges[1], vm)
        })
    },
    // 设置新值
    setVal(expre, vm, inputVal) {
        return expre.split('.').reduce((data, currentVal) => {
            return data[currentVal] = inputVal
        }, vm.$data)
    },

    // 指令解析:v-test
    test(node, expre, vm) {
        let value;
        if(expre.indexOf('{{') !== -1) {
            // 正则匹配{{}}里的内容
            value = expre.replace(/\{\{(.+?)\}\}/g, (...arges) => {

                // new watcher这里相关的先可以不看,等后面讲解写到观察者再回头看。这里是绑定观察者实现     的效果是通过改变数据会触发视图,即数据=》视图。
                // 没有new watcher 不影响视图初始化(页面参数的替换渲染)。
                // 订阅数据变化,绑定更新函数。
                new watcher(vm, arges[1], () => {
                    // 确保 {{person.name}}----{{person.fav}} 不会因为一个参数变化都被成新值
                    this.updater.textUpdater(node, this.getgetContentVal(expre,vm))
                })

                return this.getVal(arges[1],vm)
            })
        } else {
            // 同上,先不看
            // 数据=》视图
            new watcher(vm, expre, (newVal) => {
            // 找不到{}说明是test指令,所以当前节点只有一个参数变化,直接用回调函数传入的新值
        this.updater.textUpdater(node, newVal)
          })

            value = this.getVal(expre,vm)
        }

        // 将数据替换,更新到视图上
        this.updater.textUpdater(node,value)
    },
    //指令解析: v-html
    html(node, expre, vm) {
        const value = this.getVal(expre, vm)

        // 同上,先不看
        // 绑定观察者 数据=》视图
        new watcher(vm, expre (newVal) => {
            this.updater.htmlUpdater(node, newVal)
        })

        // 将数据替换,更新到视图上
        this.updater.htmlUpdater(node, newVal)
    },
    // 指令解析:v-mode
    model(node,expre, vm) {
        const value = this.getVal(expre, vm)

        // 同上,先不看
        // 绑定观察者 数据=》视图
        new watcher(vm, expre, (newVal) => {
            this.updater.modelUpdater(node, newVal)
        })

        // input框  视图=》数据=》视图
        node.addEventListener('input', (e) => {
            //设置新值 - 将input值赋值到v-model绑定的参数上
            this.setVal(expre, vm, e.traget.value)
        })
        // 将数据替换,更新到视图上
        this.updater.modelUpdater(node, value)
    },
    // 指令解析: v-on
    on(node, expre, vm, eventName) {
        // 或者指令绑定的事件函数
        let fn = vm.$option.methods && vm.$options.methods[expre]
        // 监听函数并调用
        node.addEventListener(eventName,fn.bind(vm),false)
    },
    // 指令解析: v-bind
    bind(node, expre, vm, attrName) {
        const value = this.getVal(expre,vm)
        this.updater.bindUpdate(node, attrName, value)
    }

// updater对象,管理不同指令对应的更新方法
updater: {
        // v-text指令对应更新方法
        textUpdater(node, value) {
            node.textContent = value
        },
        // v-html指令对应更新方法
        htmlUpdater(node, value) {
            node.innerHTML = value
        },
        // v-model指令对应更新方法
        modelUpdater(node,value) {
            node.value = value
        },
        // v-bind指令对应更新方法
        bindUpdate(node, attrName, value) {
            node[attrName] = value
        }
    },
}

3. Implement data hijacking and monitoring

#We have data monitoring, and we also need an observer to trigger the update view. Because data changes are required to trigger updates, a bridge Dep is needed to collect all observers (observer collection) and connect Observer and Watcher. Data changes notify Dep, and Dep notifies the corresponding observer to update the view.

Observer.js

// 定义一个观察者
class watcher {
    constructor(vm, expre, cb) {
        this.vm = vm
        this.expre = expre
        this.cb =cb
        // 把旧值保存起来
        this.oldVal = this.getOldVal()
    }
    // 获取旧值
    getOldVal() {
        // 将watcher放到targe值中
        Dep.target = this
        // 获取旧值
        const oldVal = compileUtil.getVal(this.expre, this.vm)
        // 将target值清空
        Dep.target = null
        return oldVal
    }
    // 更新函数
    update() {
        const newVal =  compileUtil.getVal(this.expre, this.vm)
        if(newVal !== this.oldVal) {
            this.cb(newVal)
        }
    }
}
// 定义一个观察者集合
class Dep {
    constructor() {
        this.subs = []
    }
    // 收集观察者
    addSub(watcher) {
        this.subs.push(watcher)
    }
    //通知观察者去更新
    notify() {
        this.subs.forEach(w => w.update())
    }
}
// 定义一个Observer类通过gettr,setter实现数据的监听绑定
class Observer {
    constructor(data) {
        this.observer(data)
    }

    // 定义函数解析data,实现数据劫持
    observer (data) {
        if(data && typeof data === 'object') {
            // 是对象遍历对象写入getter,setter方法
            Reflect.ownKeys(data).forEach(key => {
                this.defineReactive(data, key, data[key]);
            })
        }
    }

    // 数据劫持方法
    defineReactive(obj,key, value) {
        // 递归遍历
        this.observer(data)
        // 实例化一个dep对象
        const dep = new Dep()
        // 通过ES5的API实现数据劫持
        Object.defineProperty(obj, key, {
            enumerable: true,
            configurable: false,
            get() {
                // 当读当前值的时候,会触发。
                // 订阅数据变化时,往Dep中添加观察者
                Dep.target && dep.addSub(Dep.target)
                return value
            },
            set: (newValue) => {
                // 对新数据进行劫持监听
                this.observer(newValue)
                if(newValue !== value) {
                    value = newValue
                }
                // 告诉dep通知变化
                dep.notify()
            }
        })
    }

}
Recommended tutorial: "

JavaScript Video Tutorial"

The above is the detailed content of Detailed explanation of MVVM principles and implementation methods in Vue. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
Vue常见面试题汇总(附答案解析)Vue常见面试题汇总(附答案解析)Apr 08, 2021 pm 07:54 PM

本篇文章给大家分享一些Vue面试题(附答案解析)。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

5 款适合国内使用的 Vue 移动端 UI 组件库5 款适合国内使用的 Vue 移动端 UI 组件库May 05, 2022 pm 09:11 PM

本篇文章给大家分享5 款适合国内使用的 Vue 移动端 UI 组件库,希望对大家有所帮助!

vue中props可以传递函数吗vue中props可以传递函数吗Jun 16, 2022 am 10:39 AM

vue中props可以传递函数;vue中可以将字符串、数组、数字和对象作为props传递,props主要用于组件的传值,目的为了接收外面传过来的数据,语法为“export default {methods: {myFunction() {// ...}}};”。

手把手带你利用vue3.x绘制流程图手把手带你利用vue3.x绘制流程图Jun 08, 2022 am 11:57 AM

利用vue3.x怎么绘制流程图?下面本篇文章给大家分享基于 vue3.x 的流程图绘制方法,希望对大家有所帮助!

聊聊vue指令中的修饰符,常用事件修饰符总结聊聊vue指令中的修饰符,常用事件修饰符总结May 09, 2022 am 11:07 AM

本篇文章带大家聊聊vue指令中的修饰符,对比一下vue中的指令修饰符和dom事件中的event对象,介绍一下常用的事件修饰符,希望对大家有所帮助!

如何覆盖组件库样式?React和Vue项目的解决方法浅析如何覆盖组件库样式?React和Vue项目的解决方法浅析May 16, 2022 am 11:15 AM

如何覆盖组件库样式?下面本篇文章给大家介绍一下React和Vue项目中优雅地覆盖组件库样式的方法,希望对大家有所帮助!

通过9个Vue3 组件库,看看聊前端的流行趋势!通过9个Vue3 组件库,看看聊前端的流行趋势!May 07, 2022 am 11:31 AM

本篇文章给大家分享9个开源的 Vue3 组件库,通过它们聊聊发现的前端的流行趋势,希望对大家有所帮助!

react与vue的虚拟dom有什么区别react与vue的虚拟dom有什么区别Apr 22, 2022 am 11:11 AM

react与vue的虚拟dom没有区别;react和vue的虚拟dom都是用js对象来模拟真实DOM,用虚拟DOM的diff来最小化更新真实DOM,可以减小不必要的性能损耗,按颗粒度分为不同的类型比较同层级dom节点,进行增、删、移的操作。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version