Vue:nextTick作用 - 附带案例讲解

x33g5p2x  于2022-03-06 转载在 其他  
字(2.3k)|赞(0)|评价(0)|浏览(275)

1. Vue.$nextTick - 获取最新渲染的DOM数据

参考:https://segmentfault.com/a/1190000012861862

通俗解释:Vue 在修改数据后,视图不会立刻更新,而是等同一事件循环中的所有数据变化完成之后,再统一进行视图更新 - 即你修改下图变量message是同步任务,但你把数据渲染到页面是异步任务(Vue的视图渲染内部用虚拟DOM组成),只要虚拟DOM更新了数据,那么你就可以获取到最新的渲染数据

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <script src="G:\VsCode\开源\vue.global.js"></script>
  9. </head>
  10. <body>
  11. <div id="main-box">
  12. <div style="margin-top:50px;border: 5px solid red;padding:30px">
  13. <p ref="sourceContent">{{msg}}</p>
  14. <p>不使用nextTick获取的sourceContent节点的内容:{{msg2}}</p>
  15. <p>使用nextTick获取的sourceContent节点的内容:{{msg3}}</p>
  16. <button @click="test">测试$nextTick</button>
  17. </div>
  18. <div style="margin-top:50px;border: 5px solid red;padding:30px">
  19. <div>
  20. <button @click="switchShow">隐藏/显示Input框, 显示时此Input获得焦点(不使用nextTick)</button>
  21. <br>
  22. <span>不使用nextTick</span><input ref="input" v-if="show"></input>
  23. </div>
  24. <div style="margin-top:50px">
  25. <button @click="switchShow2">隐藏/显示Input框, 显示时此Input获得焦点(使用nextTick)</button>
  26. <br>
  27. <span>使用nextTick</span><input ref="input2" v-if="show2"></input>
  28. </div>
  29. </div>
  30. </div>
  31. </body>
  32. <script>
  33. var mainPage = {
  34. data: function () {
  35. return {
  36. msg: "原始信息",
  37. msg2: "",
  38. msg3: "",
  39. num: 1,
  40. show: false,
  41. show2: false
  42. }
  43. },
  44. methods: {
  45. test: function () {
  46. this.msg = "新消息" + this.num++
  47. //还没等sourceContent节点渲染完就去拿到节点HTML内容
  48. this.msg2 = this.$refs['sourceContent'].innerHTML
  49. //等到sourceContent节点渲染完才去拿节点HTML内容
  50. this.$nextTick(() => {
  51. this.msg3 = this.$refs['sourceContent'].innerHTML
  52. })
  53. },
  54. //此input不会获得焦点,因为input还没渲染出来已经去执行focus方法
  55. switchShow: function () {
  56. this.show = !this.show;
  57. if (this.show) {
  58. this.$refs['input'].focus();
  59. }
  60. },
  61. //此input会获得焦点,因为input渲染出来才去执行focus方法
  62. switchShow2: function () {
  63. this.show2 = !this.show2;
  64. if (this.show2) {
  65. this.$nextTick(() => {
  66. this.$refs['input2'].focus();
  67. })
  68. }
  69. },
  70. }
  71. }
  72. Vue.createApp(mainPage)
  73. .mount("#main-box")
  74. </script>
  75. </html>

相关文章