vue实现url的传递
使用路由参数传递URL
在Vue中,可以通过Vue Router的路由参数实现URL传递。在路由配置中定义动态参数,例如:
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User }
]
})
组件中通过this.$route.params.id获取参数值。导航时使用router.push({ name: 'user', params: { id: 123 }})传递参数。
使用查询参数传递URL
通过查询字符串传递参数,路由配置无需特殊定义:
this.$router.push({ path: '/user', query: { id: '123' }})
组件中通过this.$route.query.id获取查询参数。这种方式会在URL中显示为/user?id=123。
使用props解耦路由参数
在路由配置中启用props转换,使路由参数作为组件的props传递:

const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User, props: true }
]
})
组件中直接声明props接收:
export default {
props: ['id']
}
通过事件总线传递URL
创建全局事件总线实现非父子组件通信:
// main.js
Vue.prototype.$eventBus = new Vue()
// 发送方
this.$eventBus.$emit('url-change', url)
// 接收方
this.$eventBus.$on('url-change', url => {
console.log(url)
})
使用Vuex状态管理
在store中定义状态和mutations:

const store = new Vuex.Store({
state: {
currentUrl: ''
},
mutations: {
setUrl(state, url) {
state.currentUrl = url
}
}
})
组件中通过this.$store.commit('setUrl', url)设置URL,通过this.$store.state.currentUrl获取URL。
通过本地存储传递
使用localStorage或sessionStorage临时存储URL:
// 存储
localStorage.setItem('tempUrl', url)
// 获取
const url = localStorage.getItem('tempUrl')
注意清除不再需要的数据:
localStorage.removeItem('tempUrl')






