Home > Article > Web Front-end > Detailed explanation of Vue + Vuex using vm.$nextTick instance
This article mainly introduces the detailed explanation of how to use vm.$nextTick in Vue + Vuex. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.
vm.$nextTick
Simply put, because the DOM will at least be updated after all the codes in the current tick have been executed. Therefore, it is impossible to execute after the data is modified and the DOM is updated. 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), In this way, after the DOM is updated, this code will be executed immediately.
//改变数据 vm.message = 'changed' //想要立即使用更新后的DOM。这样不行,因为设置message后DOM还没有更新 console.log(vm.$el.textContent) // 并不会得到'changed' //这样可以,nextTick里面的代码会在DOM更新后执行 Vue.nextTick(function(){ console.log(vm.$el.textContent) //可以得到'changed' })
The function of vm.$nextTick is to delay the execution of the callback until the next DOM update cycle.
Normally obtain data in ready/mounted, then the operation is very simple
ready() { // vue2 为 mounted() { var request = $.ajax({ type: "POST", dataType: 'json', url: "api.php" }); request.then((json) => { // balabala this.$nextTick(function () { // balabala }) }); }
If you are using vuex, due to the vuex data The operations are all in action and mutations, and then the function in action is called in ready/mounted. So how to use vm.$nextTick at this time?
At this time we need to use Promise, the specific code is as follows :
The home page is api.js
export default { getFromConfig(config) { return $.ajax({ data: config }) } }
Then there is action.js
export const getArticleList = ({dispatch}, config) => { return api.getFromConfig(config).then(({data}) => { dispatch(types.RECEIVE_ARTICLE, data, config.page) }) }
Return must be added here, so that a Promise object can be returned
Finally, the vue component
methods: { loadMore(page = this.page) { var id = this.$route.params.id || "" Promise.all([ this.getArticleList({ id: id, page: page }) ]).then(() => { this.$nextTick(function () { // balabala }) }) } }
Related recommendations :
Learn simple vuex and modularization
Vuex improvement learning sharing
About Vuex’s family bucket status management
The above is the detailed content of Detailed explanation of Vue + Vuex using vm.$nextTick instance. For more information, please follow other related articles on the PHP Chinese website!