「短文」如何在 Vue 中复制文本到剪贴板
November 04, 2022
1 min
nextTick() 函数允许您在数据状态发生改变重新渲染界面时执行相应的代码,将回调传递给 nextTick(),Vue 将在更新 DOM 后立即执行回调。如下段代码所示。
const app = new Vue({ data: () => ({ text: 'First' }), template: `<h1>{{text}}</h1>`, mounted: function() { this.text = 'Second'; // Prints 'First', because Vue hasn't updated the DOM yet console.log(this.$el.textContent); this.$nextTick(() => { // Prints 'Second', because Vue has updated the DOM console.log(this.$el.textContent); }); } });
或者,您可以使用 Vue.nextTick(),它与 this.$nextTick() 是一样的。
const app = new Vue({ data: () => ({ text: 'First' }), template: `<h1>{{text}}</h1>`, mounted: function() { this.text = 'Second'; // Prints 'First', because Vue hasn't updated the DOM yet console.log(this.$el.textContent); Vue.nextTick(() => { // Prints 'Second', because Vue has updated the DOM console.log(this.$el.textContent); }); } });
Vue 的 nextTick() 优于浏览器的 setTimeout() 函数的一个优点是 nextTick() 返回一个 promise 承诺,因此您可以使用 await。
const app =new Vue({ data: () => ({ text: 'First' }), template: `<h1>{{text}}</h1>`, mounted:asyncfunction() { this.text = 'Second'; // Prints 'First', because Vue hasn't updated the DOM yetconsole.log(this.$el.textContent); await Vue.nextTick(); // Prints 'Second', because Vue has updated the DOMconsole.log(this.$el.textContent); } });
注:本文属于原创文章,版权属于「前端达人」公众号及 qianduandaren.com 所有,未经授权,谢绝一切形式的转载