Home > Web Front-end > JS Tutorial > body text

The principle of mvvm mode implementation in js (with code)

不言
Release: 2018-09-30 15:50:38
forward
3243 people have browsed it

The content of this article is about the principle of mvvm mode implementation in js (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Take the Vue.js framework as an example, the mvvm mode used

The principle of mvvm mode implementation in js (with code)
view refers to the page A view composed of html and css.
model refers to the data model obtained from the backend
viewmodel refers to the view data layer generated and maintained by the front-end developer organization. This layer contains view behavior and data.
View behavior refers to what is requested when the page is loaded, placing the specified data on the specified element, and clicking an element to trigger an event. When the viewmodel is processed, the corresponding data will be displayed to the view layer.

The advantage of the MVVM model is that when the view and viewmodel are two-way bound, there is no need to modify the DOM structure when the data changes.
For example, in native js, to bind the value of an input to the text of another div, you first need to listen to the input event, and each change triggers the modification of the text sub-node of the div node. Using the MVVM mode, you can automatically detect changes in data and modify the div text

The implementation principle of mvvm: Use Object.defineProperty(), which has two attribute methods, get and set, to obtain the object attributes. Value, reassign the object properties

//定义一个对象
let obj = {}
Object.defineProperty(obj,'txt'{
    //obj.txt属性赋值方法,同时为input、p文本赋同一个值
    set(val){
       document.getElementById('input').value = val
       document.getElementById('output').innerHTML = val
    },
    //获取txt属性的方法
    get(){
        return obj;
    }
})
//监听事件 触发的时候会给obj.txt重新赋值,从而实现双向绑定
 document.addEventListener('keyup',(e)=>{
   obj.txt = e.target.value;
 })
Copy after login

The above is the detailed content of The principle of mvvm mode implementation in js (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template