Vue-router是Vue.js官方的路由管理插件,可以實現單頁面的應用效果,同時Vue-router支持兩種模式:hash模式和history模式。下面我們從多個方面詳細闡述Vue-router的這兩種模式。
一、hash模式
hash模式是Vue-router的默認模式,使用URL中的hash(#)來模擬URL的變化,不會導致頁面的刷新,從而實現頁面的動態切換。
1、初始化
在啟動Vue.js應用時,需要先安裝Vuex和Vue-router插件,在main.js中初始化Vue-router並掛載到Vue實例上。
import VueRouter from 'vue-router';
Vue.use(VueRouter);
const router = new VueRouter({
mode: 'hash',
routes: [
{
path: '/',
component: Home,
},
{
path: '/about',
component: About,
},
]
})
new Vue({
router,
render: h => h(App),
}).$mount('#app')
2、配置路由
在Vue-router中,通過定義路由映射關係來實現URL地址到組件的映射關係。Vue-router的路由映射關係通過routes配置項來實現。在routes中可以定義多個具體的路由信息。每個路由信息是包含了URL地址和組件模板信息的對象,其中URL地址通過path屬性定義,組件模板信息通過component屬性定義。
const router = new VueRouter({
mode: 'hash',
routes: [
{
path: '/',
component: Home,
},
{
path: '/about',
component: About,
},
]
})
3、路由跳轉
在Vue-router中,通過編程式導航或聲明式導航來實現路由的跳轉。
編程式導航:通過this.$router.push()方法實現路由的跳轉。
原創文章,作者:LSPA,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/136181.html