VUE:vue源码--v-model双向绑定原理(五颗星)
注意:
1.vue源码--v-model双向绑定原理
双向绑定原理:通过Obje.defineProperty劫持数据发生的改变,如果数据发生改变了(在set中进行赋值的),触发update方法进行更细节点内容({{str}}),从而实现数据双向绑定的原理
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>手写vue添加事件</title>
</head>
<body>
<div id="app">
<h1>{{ str }}</h1>
{{str}}
<p>{{a}}</p>
<button @click="btn">按钮</button>
<input type="text" name="" v-model="str">
</div>
<script type="text/javascript" src="newvue.js"></script>
<!-- <script type="text/javascript" src="vue.js"></script> -->
<script type="text/javascript">
new Vue({
el: '#app',
data: {
str: 'str',
a: "a"
},
beforeCreate() {
console.log('beforeCreate', this.$el, this.$data)
},
created() {
console.log('created', this.$el, this.$data)
},
beforeMount() {
console.log('beforeMount', this.$el, this.$data)
},
mounted() {
console.log('mounted', this.$el, this.$data)
},
methods: {
btn(e){
this.str="str改变了"
console.log(this.str)
}
}
})
</script>
</body>
</html>
newvue.js:
// newvue.js
class Vue{
constructor(options){
this.$options=options
this.$watchEvent={}
// 2.生命周期
if(typeof options.beforeCreate=="function"){
options.beforeCreate.apply(this)
}
// data
this.$data=options.data
this.proxyData()
this.observe()
if(typeof options.created=="function"){
options.created.apply(this)
}
if(typeof options.beforeMount=="function"){
options.beforeMount.apply(this)
}
// 节点
this.$el=document.querySelector(options.el)
// 模板解析
this.compileTemplate(this.$el)
if(typeof options.mounted=="function"){
options.mounted.apply(this)
}
}
// 4.数据劫持
// 给Vue大对象赋属性,来
剩余60%内容,订阅专栏后可继续查看/也可单篇购买
前端面试题 文章被收录于专栏
前端面试的一些常问问题、问题的具体实现(可直接运行)以及底层原理