Vue 监听路由变化的三种方式
生活随笔
收集整理的這篇文章主要介紹了
Vue 监听路由变化的三种方式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
方法一:通過 watch
// 監聽,當路由發生變化的時候執行
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是用來阻止“復用”的。Vue 為你提供了一種方式來聲明“這兩個元素是完全獨立的——不要復用它們”。只需添加一個具有唯一值的?
key?屬性即可(Vue文檔原話)
<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>
?
總結
以上是生活随笔為你收集整理的Vue 监听路由变化的三种方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【通用CSS模板】移动端H5页面统一样式
- 下一篇: Vue父组件调用子组件的方法并传参的两种