一、
// 監聽,當路由發生變化的時候執行 watch:{ $route(to,from){ console.log(to.path); } }, // // 或監聽,當路由發生變化的時候執行 watch: { $route: { handler: function(val, oldVal){ console.log(val); }, // 深度觀察監聽 deep: true } }, //或監聽,當路由發生變化的時候執行 watch: { '$route':'getPath' }, methods: { getPath(){ console.log(this.$route.path); } }
二、
//key是用來阻止“復用”的。 <router-view :key="key"></router-view> computed: { key() { return this.$route.name !== undefined? this.$route.name +new Date(): this.$route +new Date() } } //注:使用computed屬性和Date()可以保證每一次的key都是不同的,這樣就可以如願刷新數據了。
三、通過 vue-router 的鈎子函數 beforeRouteEnter beforeRouteUpdate beforeRouteLeave
<script> // 引入 Tabbar組件 import mTabbar from './components/Tabbar' import mTabbarItem from './components/TabbarItem' // 引入 vuex 的兩個方法 import {mapGetters, mapActions} from 'vuex' export default { name: 'app', // 計算屬性 computed:mapGetters([ // 從 getters 中獲取值 'tabbarShow' ]), // 監聽,當路由發生變化的時候執行 watch:{ $route(to,from){ if(to.path == '/' || to.path == '/Prisoner' || to.path == '/Goods' || to.path == '/Time' || to.path == '/Mine'){ /** * $store來自Store對象 * dispatch 向 actions 發起請求 */ this.$store.dispatch('showTabBar'); }else{ this.$store.dispatch('hideTabBar'); } } }, beforeRouteEnter (to, from, next) { // 在渲染該組件的對應路由被 confirm 前調用 // 不!能!獲取組件實例 `this` // 因為當鈎子執行前,組件實例還沒被創建 }, beforeRouteUpdate (to, from, next) { // 在當前路由改變,但是該組件被復用時調用 // 舉例來說,對於一個帶有動態參數的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉的時候, // 由於會渲染同樣的 Foo 組件,因此組件實例會被復用。而這個鈎子就會在這個情況下被調用。 // 可以訪問組件實例 `this` }, beforeRouteLeave (to, from, next) { // 導航離開該組件的對應路由時調用 // 可以訪問組件實例 `this` }, components:{ mTabbar, mTabbarItem }, data() { return { select:"Building" } } } </script>