<template>
<section>
<div ref="hello">
<h1>{{name}}</h1>
</div>
<button @click="get">点击</button>
</section>
</template>
<script>
export default{
data(){
return{
name:'库里'
}
},
created(){
// 1、created中的同步代码先执行
console.log(111)
console.log(this.$refs['hello'])
// 3、created()里使用this.$nextTick()可以等待dom生成以后再来获取dom对象。
// 在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM。
this.$nextTick(()=>{
console.log(222)
console.log(this.$refs['hello']);
})
},
mounted(){
// mounted 不会承诺所有的子组件也都一起被挂载。如果你希望等到整个视图都渲染完毕,
// 可以用 vm.$nextTick 替换掉 mounted。
// mounted中
console.log(333)
console.log(this.$refs['hello'])
// 4、执行完子组件的Mounted后会立即执行父组件的mounted函数,
// 也就是说mounted函数直接是同步执行的
//但是我们的页面渲染是一个异步操作
// 也就说说执行父组件的mounted方法时,页面还没有渲染完成,
// 所以导致了打印结果不一致
this.$nextTick(()=>{
console.log(444)
console.log(this.$refs['hello'])
})
},
methods:{
get(){
this.name='詹姆斯'
//同步执行代码,此时DOM并未来的及更新
console.log(this.$refs['hello'].innerText);
//在DOM更新后立即执行
this.$nextTick(()=>{
console.log(this.$refs['hello'].innerText)
})
}
}
}
</script>
初始mounted created之后的执行结果
点击按钮后的执行结果
链接:
https://www.shuzhiduo.com/A/rV57yQ6XzP/
https://baijiahao.baidu.com/s?id=1744468847076684281&wfr=spider&for=pc