您当前位置: 南顺网络>> 官方资讯>> 建站知识

原生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, // 是否可枚举

configurable: true, // 是否可以删除目标属性或是否可以再次修改属性的特性

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