Tick and NextTick

如果使用了observe,数据更改之后视图不是立即变更,如果你想获取真实变更后的dom,你可以使用tick或者nextTick。

  1. import { render, WeElement, define, tick, nextTick } from 'omi'
  2. define('todo-list', class extends WeElement {
  3. render(props) {
  4. return (
  5. <ul>
  6. {props.items.map(item => (
  7. <li key={item.id}>{item.text}</li>
  8. ))}
  9. </ul>
  10. )
  11. }
  12. })
  13. define('todo-app', class extends WeElement {
  14. static observe = true
  15. static get data() {
  16. return { items: [], text: '' }
  17. }
  18. install() {
  19. tick(() => {
  20. console.log('tick')
  21. })
  22. tick(() => {
  23. console.log('tick2')
  24. })
  25. }
  26. beforeRender() {
  27. nextTick(() => {
  28. console.log('nextTick')
  29. })
  30. // don't using tick in beforeRender or beforeUpdate or render or afterUpdate
  31. // tick(() => {
  32. // console.log(Math.random())
  33. // })
  34. }
  35. installed() {
  36. console.log('installed')
  37. }
  38. render() {
  39. console.log('render')
  40. return (
  41. <div>
  42. <h3>TODO</h3>
  43. <todo-list items={this.data.items} />
  44. <form onSubmit={this.handleSubmit}>
  45. <input
  46. id="new-todo"
  47. onChange={this.handleChange}
  48. value={this.data.text}
  49. />
  50. <button>Add #{this.data.items.length + 1}</button>
  51. </form>
  52. </div>
  53. )
  54. }
  55. handleChange = e => {
  56. this.data.text = e.target.value
  57. }
  58. handleSubmit = e => {
  59. e.preventDefault()
  60. if (!this.data.text.trim().length) {
  61. return
  62. }
  63. this.data.items.push({
  64. text: this.data.text,
  65. id: Date.now()
  66. })
  67. this.data.text = ''
  68. }
  69. })
  70. render(<todo-app />, 'body')

你也可以手动执行 this.update ,然后在它后面获取真实的 dom 。