Recently I learned the front-end framework vue.js, a Javascript library that provides MVVM-style bi-directional data binding, focusing on the View layer. At its heart is the VM in MVVM, which is the ViewModel. In a Vue, if you want to construct a VM, you simply build an instance of a Vue. If you have a piece of HTML and you declare a V-model tag for an input control, the Vue knows that this is an input and that the input is the message property of the corresponding data.

<div id="app">
<p>{{message}}</p>
<input v-model="message">
</div>
Copy the code
Var vm = new Vue({//vm mount point el:'#app',
data: {
message:"this is a message"},... })Copy the code

In this way, the DOM(View) and data(Model) are connected. When the input field changes its content, the value of data.message will change accordingly, and changing the value of data.message will change the content of the input field. The two-way binding of Vue is based on Object.defineProperty() to hijack the setter and getter of each property, publish the message to the subscriber when the data changes, and trigger the corresponding listening callback. When the listening property is changed, the setter is triggered so that the listener receives the callback. After writing some files in Vue standard format, I feel that Vue MVVM is a little different from iOS. First, in files with a. Vue suffix, the VM generally behaves in , with immutable property, which is the data passed as the parent node view, and mutable data, which is the variable of the component itself. Methods are similar to objective-C class methods, watch is similar to KVO, components child components, and the component lifecycle method beforeCreate. A View is a collection of HTML and CSS. They’re all in one file. In iOS jobs, it’s common to pull out the VM and put it in a file. Second, due to the special nature of the ViewController in iOS (itself coupled to the View), the main function of the VM is to separate network requests and data computations, which is less functional than Vue. So the best thing to do is to rewrite the ViewController’s view by -(void)loadView to strip the view from the ViewController. And then you write the logic of the ViewModel in the ViewController.