this.$nextTick()
this.$nextTick()将回调延迟到下次 DOM 更新循环之后执行。它跟全局方法 Vue.nextTick 一样,不同的是回调的 this 自动绑定到调用它的实例上
假设我们修改了某个DOM内部的文本,我们想要打印更改后的DOM文本内容是需要等待DOM更新的,但是我们不确定DOM何时更新完成,这时,使用this.$nextTick()就可以获取到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">
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<title>this.$nextTick()</title>
<style>
div {
border: 1px solid;
padding: 10px;
text-align: center;
}
</style>
</head>
<body>
<div id="app">
<div ref="hello">
<h1>Hello World ~</h1>
</div>
<button @click="get">打印测试</button>
</div>
<script>
var app = new Vue({
el: "#app",
methods: {
get() {
console.log("打印测试")
}
},
created() {
console.log("没有使用this.$nextTick,我们是无法在created中获取dom节点的");
console.log(this.$refs['hello']);
this.$nextTick(() => {
console.log("在这里我们可以获取到dom节点");
console.log(this.$refs['hello']);
});
},
});
</script>
</body>
</html>
下一段示例代码:
<!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">
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<title>this.$nextTick()</title>
<style>
div {
border: 1px solid;
padding: 10px;
text-align: center;
}
</style>
</head>
<body>
<div id="app">
<div ref="hello">
<h1>{{value}}</h1>
</div>
<button @click="get">打印测试</button>
</div>
<script>
var app = new Vue({
el: "#app",
data() {
return {
value: "Hello World ~"
}
},
methods: {
get() {
this.value = "dom内部的文本内容已经改变了~";
console.log(this.$refs['hello'].innerText);
this.$nextTick(() => {
console.log(this.$refs['hello'].innerText);
});
}
},
});
</script>
</body>
</html>
参考网址:
有需要更正的地方各位看官可以在评论里面指出!