您當前位置: 南順網絡>> 官方資訊>> 建站知識

原生js實現Vue雙向數據綁定

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<meta http-equiv="X-UA-Compatible" content="ie=edge">

<title>vue</title>

</head>

<body>

<div id="app">

<form>

<input type="text" v-model="number">

<div v-bind="number"></div>

<button type="button">增加</button>

</form>

</div>

<script>

function myVue (options) {

this._init(options)

}

myVue.prototype._obverse = function (obj) {

for (const key in obj) {

if (obj.hasOwnProperty(key)) {

let value = obj[key];

Object.defineProperty(this.$data, key, {

enumerable: true, // 是否可(kě)枚舉

configurable: true, // 是否可(kě)以删除目标屬性或是否可(kě)以再次修改屬性的(de)特性

get () {

console.log(`獲取${value}`)

return value

},

set (newVal) {

document.querySelector('*[v-model=number]').value = newVal

document.querySelector('*[v-bind=number]').innerHTML = newVal

if (value !== newVal) {

value = newVal

}

}

})

}

}

}

myVue.prototype._init = function (options) {

this.$options = options

this.$el = document.querySelector(options.el)

this.$data = options.data

this.methods = options.methods


this._obverse(this.$data)

}


var vm = new myVue({

el: '#app',

data: {

number: 0,

}

})

document.querySelector('input').oninput = function (e) {

vm.$data.number = e.target.value

}

document.querySelector('button').onclick = function () {

vm.$data.number++

}

</script>

</body>

</html>


編輯:--ns868