Views: 3940
Last Modified: 15.02.2023
What is VueRouter
VueRouter – official routing library for Vue.js. It's closely integrated with Vue.js core, which allows to easily create SPA applications.
VueRouter includes the following features:
- Embedded routes/views
- Router modular configuration
- Access to the route parameters, query, wildcards
- Transition animations for Vue.js based views
- Convenient navigation management
- Automatic inserting of active CSS class for links
- HTML5 history work modes
- Configurable page scrolling behavior
You can read more about the library at the official website.
Connecting and launching
To start the work, connect the extension ui.vue3.router
in your extension or php-enabled page.
Import createRouter and other necessary functions to your extension. For example, import createWebHashHistory from ui.vue3.router
:
import {BitrixVue} from 'ui.vue3';
import {createRouter, createWebHashHistory} from 'ui.vue3.router';
const router = createRouter({
...
});
const application = BitrixVue.createApp({
components: {
Component
},
template: `
<Component/>
`
});
application.use(router);
application.mount('#application');
Use the namespace BX.Vue3.VueRouter
for function access and handling the page and scripts without transpiling (for example, for createRouter its BX.Vue3.VueRouter.createRouter
).
Example
import {BitrixVue} from 'ui.vue3';
import {createRouter, createWebHashHistory} from 'ui.vue3.router';
// 1. Define components for routes.
// They can be imported from other files
const Foo = { template: '<div>Page1</div>' };
const Bar = { template: '<div>Page2</div>' };
// 2. Define several routes
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
];
// 3. Create a router instance and pass routes to the `routes` options
const router = createRouter({
history: createWebHashHistory(),
routes,
});
// 4. Create and mount the app's root instance.
const application = BitrixVue.createApp({
template: `
<div>
<h3>VueRouter</h3>
<div>
<router-link to="/foo">Go to Page1</router-link> -
<router-link to="/bar">Go to Page2</router-link>
</div>
<router-view></router-view>
</div>
`
});
application.use(router);
application.mount('#application');