vue雙向資料繫結核心原理基本模擬實現

2021-09-10 04:46:49 字數 2378 閱讀 9004

vue雙向資料繫結主要是通過 object物件的defineproperty屬性,重寫data的set和get函式來實現的,這裡只會實現最基本的內容,主要實現v-model,v-bind 和v-click三個命令,其他命令也可以自行補充

<

!doctype html>

"utf-8"

/>

"x-ua-compatible" content=

"ie=edge"

>

myvue雙向資料繫結<

/title>

"viewport" content=

"width=device-width, initial-scale=1"

>

<

/head>

>

"text" v-model=

"number"

/>

"button" v-click=

"increment"

>增加<

/button>

<

/form>

"number"

>

<

/h3>

<

/div>

window.

onload

=function()

, methods:}}

);}// 定義myvue建構函式

function

myvue

(options)

// 定義_init初始化函式

myvue.prototype.

_init

=function

(options)

;// 呼叫_observe函式對data進行處理

this

._observe

(this

.$data)

;// 用來解析指令(v-model,v-click,v-bind等指令),在過程中並對view和model進行繫結

this

._compile

(this

.$el);}

// 實現_observe函式

myvue.prototype.

_observe

=function

(obj)

this

._binding[key]

= value=obj[key]

;//獲取物件的屬性值if(

typeof value ===

'object'

)var binding=

this

._binding[key]

;//定義變數binding來快取遍歷到的物件對應的指令集

object.

defineproperty

(obj,key,

,set

:function

(newval));

}}})

;}}}

// 實現_compile函式

myvue.prototype.

_compile

=function

(root)

if(node.

hasattribute

('v-click'))

)()}

if(node.

hasattribute

('v-model')&&

(node.tagname ==

'input'

|| node.tagname ==

'textarea'))

var attrval=node.

getattribute

('v-model');

_this._binding[attrval]

._directives.

push

(new

watch

('input'

, node,

_this,

attrval,

'value'))

return

function()

})(i));}

if(node.

hasattribute

('v-bind'))

}}// 定義乙個watch類

function

watch

(name,el,vm,exp,attr)

watch.prototype.

update

=function()

<

/script>

<

/body>

<

/html>

vue雙向資料繫結原理

vue應用的是mvvm框架,view和model分離,然後通過vm雙向資料繫結,div 原生物件即資料 var data 建立乙個 viewmodel 例項 var vm new vue 然而乙個動態資料的繫結,是怎麼實現的呢,首先vue利用es5的defineproperty方法裡的get,set...

vue雙向資料繫結原理

text id text show p var text document.getelementbyid text show document.getelementbyid show var model object.defineproperty model,name set function ne...

vue資料雙向繫結原理

vue的資料雙向繫結的小例子 html index.js function selfvue data,el,exp 對data的每一層級的屬性進行監聽,如果變化執行notify observe data 初始化模板資料的值 el.innerhtml this data exp new watcher...