SoFunction
Updated on 2025-04-03

Explain details on how to use vm.$nextTick in Vue + Vuex

vm.$nextTick

Simply put, because at least all the code in the current tick will be updated after it is executed. Therefore, it is impossible to execute after modifying the data and update the DOM. To ensure that a certain piece of code is executed after the DOM is updated, this piece of code must be placed in the next event loop, such as setTimeout(fn, 0), so that after the DOM is updated, this piece of code will be executed immediately.

//Change data = 'changed' 
 
// Want to use the updated DOM immediately.  This won't work, because the DOM has not been updated after setting the message(vm.$) // I won't get 'changed' 
//This is OK. The code in nextTick will be executed after the DOM is updated.(function(){ 
  (vm.$) //You can get 'changed'}) 

The purpose of vm.$nextTick is to delay the callback until the next DOM update loop is executed.

Normally obtaining data in ready/mounted, then the operation is very simple

ready() { // vue2 is mounted() {  var request = $.ajax({
    type: "POST",
    dataType: 'json',
    url: ""
  });
  ((json) => {
    // balabala
    this.$nextTick(function () {
      // balabala
    })
  });
}

If you use vuex, since vuex's data operations are all in action and mutations, and then the function in action is called in ready/mounted, then how should you use vm.$nextTick at this time?

At this time, we need to use Promise, the specific code is as follows:

Home page is

export default {
  getFromConfig(config) {
    return $.ajax({ data: config })
  }
}

Then

export const getArticleList = ({dispatch}, config) => {
  return (config).then(({data}) => {
    dispatch(types.RECEIVE_ARTICLE, data, )
  })
}

You must add return here, so that you can return a Promise object

Finally, the vue component

methods: {
  loadMore(page = ) {
    var id = this.$ || ""
    ([
      ({
        id: id,
        page: page
      })
    ]).then(() => {
      this.$nextTick(function () {
        // balabala
      })
    })
  }
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.