vue响应式原理与生命周期
文章目录
vue响应式原理与生命周期前言一、vue响应式原理二、生命周期
前言
提示:读完以下的内容,你将可以回答如下问题:响应式原理:如何修改声明式变量?当声明变量发生变化时,在哪个时间节点去更新DOM?如何理解生命周期?
提示:以下是本篇文章正文内容,下面案例可供参考
一、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>Document
</title>
</head>
<body>
<div id='app'>
<input id='ipt' type="text">
<h1 id='user'></h1>
</div>
<script>
var app = {}
var username = 'zhangsan'
Object.defineProperty(app, 'username', {
get: function() {
return username
},
set: function(newVal) {
username = newVal
Watcher(newVal)
}
})
function Watcher(newVal) {
document.getElementById('user').innerText = newVal
document.getElementById('ipt').value = newVal
}
Watcher(app.username)
document.getElementById('ipt').addEventListener('keyup', function(e){
app.username = e.target.value
})
</script>
</body>
</html>
Vue响应式底层实现方法是 Object.defineProperty() 方法,该方法中存在一个getter和setter的可选项,可以对属性值的获取和设置造成影响,Vue中编写了一个wather来处理数据,在使用getter方法时,就会通知wather,让它去更新真实的DOM 同样的,在使用setter方法时,就会在变更值的同时,通知wather,让它去更新真实的DOM
二、生命周期
<!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>生命周期
</title>
</head>
<body>
<div id='app' class='app'>
<h1>测试生命周期
</h1>
<h1 v-text='count'></h1>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
var app = new Vue({
el: '#app',
data: {
count: 1,
timer: null
},
beforeCreate() {
console.log('beforeCreate')
},
created() {
console.log('created')
},
beforeMount(){
console.log('beforeMount')
},
mounted() {
console.log('mounted')
this.timer = setInterval(function(){
console.log('1')
}, 1000)
},
beforeUpdate() {
console.log('beforeUpdate')
},
updated() {
console.log('updated')
},
beforeDestroy() {
console.log('beforeDestroy')
clearInterval(this.timer)
},
destroyed() {
console.log('destroyed')
}
})
</script>
</body>
</html>
var vm
= {
tagName
: 'div',
props
: {
id
: 'app',
class: 'app'
},
children
: [
{
tagName
: 'h1',
children
: '测试生命周期'
},
{
tagName
: 'h1',
children
: '1'
}
]
}
var vm2
= {
tagName
: 'div',
props
: {
id
: 'app',
class: 'app'
},
children
: [
{
tagName
: 'h1',
children
: '测试生命周期'
},
{
tagName
: 'h1',
children
: '2'
}
]
}
diff(vm
, vm2
)