vue-router切換時loading效果實現


實現原理

1. 可以在vuex中維護一個isLoading 的變量

2. 在 router.beforeEach 鈎子中 設置 isLoading = true , 在 router.afterEach 中 設置 isLoading = false

Vuex:

actions.js:

export default {
  onLoading(context, isLoading) {
    context.commit('setLoading', isLoading);
  }
};

mutations.js:

export default {
  setUser(state, user) {
    state.user = user;
  },
  setUserPlaylist(state, playlist) {
    state.userPlaylist = playlist;
  },
  setCount(state, count) {
    state.count = count;
  },
  setLoading(state, isLoading) { console.log(isLoading); state.isLoading = isLoading; }
};

state.js:

export default {
  user: null,
  userPlaylist: [],
  count: 0,
  isLoading: null
};

在main.js中:

router.beforeEach((to, from, next) => {
  store.dispatch('onLoading', true);
  console.log(store.state.isLoading);
  next();
});
// 這里為了讓效果明顯一些加了延時
router.afterEach((to, from) => {
  setTimeout(function() {
    store.dispatch('onLoading', false);
    console.log(store.state.isLoading);
  }, 1000);
});

3. 在根組件(即所在的父組件)上 放置一個Loading組件,例如:

 

 

computed: {
    ...mapState(['count', 'isLoading']),
    keyword() {
      return this.$route.params.keywords;
    }
  },

完成

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM