Vue 监听路由变化的三种方式
生活随笔
收集整理的這篇文章主要介紹了
Vue 监听路由变化的三种方式
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
方法一:通過(guò) watch
// 監(jiān)聽,當(dāng)路由發(fā)生變化的時(shí)候執(zhí)行
watch:{$route(to,from){console.log(to.path);}
},
或?
// 監(jiān)聽,當(dāng)路由發(fā)生變化的時(shí)候執(zhí)行
watch: {$route: {handler: function(val, oldVal){console.log(val);},// 深度觀察監(jiān)聽deep: true}
},
或
// 監(jiān)聽,當(dāng)路由發(fā)生變化的時(shí)候執(zhí)行
watch: {'$route':'getPath'
},
methods: {getPath(){console.log(this.$route.path);}
}
方法二::key是用來(lái)阻止“復(fù)用”的。Vue 為你提供了一種方式來(lái)聲明“這兩個(gè)元素是完全獨(dú)立的——不要復(fù)用它們”。只需添加一個(gè)具有唯一值的?
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都是不同的,這樣就可以如愿刷新數(shù)據(jù)了。
方法三:通過(guò) vue-router 的鉤子函數(shù)?beforeRouteEnter??beforeRouteUpdate??beforeRouteLeave
<script>// 引入 Tabbar組件import mTabbar from './components/Tabbar'import mTabbarItem from './components/TabbarItem'// 引入 vuex 的兩個(gè)方法import {mapGetters, mapActions} from 'vuex'export default {name: 'app',// 計(jì)算屬性computed:mapGetters([// 從 getters 中獲取值'tabbarShow']),// 監(jiān)聽,當(dāng)路由發(fā)生變化的時(shí)候執(zhí)行watch:{$route(to,from){if(to.path == '/' || to.path == '/Prisoner' || to.path == '/Goods' || to.path == '/Time' || to.path == '/Mine'){/*** $store來(lái)自Store對(duì)象* dispatch 向 actions 發(fā)起請(qǐng)求*/this.$store.dispatch('showTabBar');}else{this.$store.dispatch('hideTabBar');}}},beforeRouteEnter (to, from, next) {// 在渲染該組件的對(duì)應(yīng)路由被 confirm 前調(diào)用// 不!能!獲取組件實(shí)例 `this`// 因?yàn)楫?dāng)鉤子執(zhí)行前,組件實(shí)例還沒(méi)被創(chuàng)建},beforeRouteUpdate (to, from, next) {// 在當(dāng)前路由改變,但是該組件被復(fù)用時(shí)調(diào)用// 舉例來(lái)說(shuō),對(duì)于一個(gè)帶有動(dòng)態(tài)參數(shù)的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉(zhuǎn)的時(shí)候,// 由于會(huì)渲染同樣的 Foo 組件,因此組件實(shí)例會(huì)被復(fù)用。而這個(gè)鉤子就會(huì)在這個(gè)情況下被調(diào)用。// 可以訪問(wèn)組件實(shí)例 `this`},beforeRouteLeave (to, from, next) {// 導(dǎo)航離開該組件的對(duì)應(yīng)路由時(shí)調(diào)用// 可以訪問(wèn)組件實(shí)例 `this`},components:{mTabbar,mTabbarItem},data() {return {select:"Building"}}}
</script>
?
總結(jié)
以上是生活随笔為你收集整理的Vue 监听路由变化的三种方式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【通用CSS模板】移动端H5页面统一样式
- 下一篇: Vue父组件调用子组件的方法并传参的两种