Proxy实现极简MVVM


<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Vuetitle>
head>
<body>
	<div id="app">
		名字:<h2>{{name}}h2>
		年龄:<h2>{{age}}h2>
		<button @click="changeName">改变namebutton>
		<button @click="changeAge">改变agebutton>
	div>
	
<script>
 	
	class Vue{
		constructor(options){
			this.$subs = []
			this.$options = options
			this.$data = options.data
			this.$methods = options.methods
			this.proxy()//data的数据绑定到this.data上,并监听data的数据

			this.$elNode = document.querySelector(this.$options.el)
			let fragment = this.nodeToFragment()
			
			this.compile(fragment.childNodes)
			this.$elNode.appendChild(fragment)
		}

		nodeToFragment() {
			let fragment = document.createDocumentFragment();
			let nodes = [...this.$elNode.childNodes]
			nodes.forEach(item=>{
				fragment.appendChild(item)
			})
			return fragment;
		}

		compile(childNodes){
			let reg = /\{\{(.*)\}\}/
			
			childNodes.forEach(item=>{
				if((item.nodeType===1||item.nodeType===3)&&reg.test(item.textContent)){
					let regval = item.textContent.replace(reg,`$1`)
					this.$subs.push({node:item,key:regval})//缓存节点数据
					let value = this.$data[regval]
					item.textContent = typeof value==='object'?JSON.stringify(value):value
				}else if(item.nodeType===1){
					let nodeAttrs = [...item.attributes]
					nodeAttrs.forEach(cell=>{
						if(cell.name.includes('@')){
							item.addEventListener(cell.name.substr(1),this.$methods[cell.value].bind(this))
						}
					})
				}
			})
		}

		proxy(){
			let that = this
			this.data = new Proxy(this.$data,{
				get(target,prop){
					return target[prop]
				},
				set(target,prop,newval){
					target[prop] = newval
					that.$subs.forEach(cell=>{
						if(cell.key===prop){
							cell.node.textContent = typeof newval === 'object'?JSON.stringify(newval):newval
							
						}
					})
				}
			})
		}
	}

	new Vue({
		el:'#app',
		data:{
			name:'李白',
			age:[1,2,3]
		},
		methods:{
			changeName(){
				this.data.name = '杜甫'
			},
			changeAge(){
				this.data.age = ['a','b','c']
			},
			change(){
				
			}
		}

	})
	
script>
body>
html>

你可能感兴趣的:(Proxy实现极简MVVM)