Vue之nextTick()

我们有时候操作 DOM,是想在 data 数据变更的时候进行操作。

那么,我们应该怎么做呢?

index.html

<!DOCTYPE html>
<html lang="en">

<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Vue 学习</title> </head> <body> <!-- 2. Vue 挂载点 - Vue 的虚拟 DOM 在这里操作到实际渲染 --> <!-- 简单理解为 jQuery 的拼接字符串(并不全是) --> <div id="app"></div> <!-- 1. 引用 Vue --> <!-- Vue CDN - 提供 Vue 服务 --> <script src="https://cdn.bootcss.com/vue/2.5.21/vue.js"></script> <!-- Vue Router CDN - 管理路由 --> <script src="https://cdn.bootcss.com/vue-router/3.0.2/vue-router.js"></script> <!-- Axios CDN - 调用接口 --> <script src="https://cdn.bootcss.com/axios/0.18.0/axios.js"></script> <script>   var App = {  template: `  <div>  <input v-if="isShow" ref="input" />  </div>  `,  data: function() {  return {  isShow: true  }  },  mounted: function() {  // 希望在 Vue 真正渲染 DOM 到页面之后进行下面操作  this.$nextTick(function() {  this.$refs.input.focus();  })  }  }   new Vue({  el: document.getElementById('app'),  components: {  app: App  },  template: `<app/>`  })   </script> </body> </html>

如上,通过 Vue 的全局 API Vue.nextTick(),我们在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM。

这个操作我们可想象下 Promise 的执行流程,会获得更好的体验。

猜你喜欢

转载自www.cnblogs.com/ning123/p/11146289.html
今日推荐