<div id="app">
<button type="button" @click="change" ref="btn">{{content}}</button>
</div>
<script src="vue.js"></script>
<script>
const app = new Vue({
el: "#app",
data() {
return {
content: '初始值222'
}
},
methods: {
change() {
this.content = '改变了的值'
this.$nextTick(() => {
console.log(this.$refs.btn.innerText);
})
}
},
computed: {
}
})
nextTick和$nextTick区别
1.nextTick(callback):当数据发生变化,更新后执行回调。在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM。
2.$nextTick(callback):当dom发生变化,更新后执行的回调。将回调延迟到下次 DOM 更新循环之后执行。在修改数据之后立即使用它,然后等待 DOM 更新。
3.这两个方法没有太大的不同。区别在于:nextTick(callback) 是全局的方法;而 $nextTick(callback) 是回调的 this 自动绑定到调用它的实例上;所以用的更多的是$nextTick(callback)
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="app">
<div ref="hello">
<h1>Hello World ~</h1>
</div>
<button type="button" @click="get" ref="btn">{{content}}</button>
</div>
<script src="vue.js"></script>
<script>
const app = new Vue({
el: "#app",
data() {
return {
content: '初始值222'
}
},
methods: {
get() {
}
},
computed: {
},
created() {
this.$nextTick(() => {
console.log('111'); //5
console.log(this.$refs['hello']); //6
})
/* setTimeout(() => {
console.log('111');
console.log(this.$refs['hello']);
}, 0) */
console.log('111'); //1
console.log(this.$refs['hello']); //2
},
mounted() {
console.log(333); //3
console.log(this.$refs['hello']); //4
this.$nextTick(() => {
console.log(222);
console.log(this.$refs['hello']);
});
}
})
</script>