I am trying to dynamically pass in data to set the base for vue-router. Is it possible to setup a separate function elsewhere that passes in a base name variable? For example, if an editor wanted to set the base name via a CMS, I’d want a way to pass (or import) that name through.
// router/index.js
export default new VueRouter({
base: '[PASS BASE NAME HERE]',
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/contact',
name: 'Contact',
component: Contact
}
],
mode: 'history'
})
So static layout wrapper components are very powerful and flexible, but they also come with a cost. Let’s check out if we can come up with an approach which has all the positive characteristics of static wrapper components but none of the negative ones. Before we get started, let me say that the component system in Vue.js is very, very powerful.
As the name suggests, dynamic routes are far more flexible. A dynamic route lets us define multiple paths to display information according to real-time network changes. We can use dynamic routing to make URLs more memorable and user-friendly, creating pages that are similar but contain different data.
We can use dynamic components, to build a very flexible yet performant dynamic layout system. First of all, let’s update our App base component to prepare it for dynamic layouts. In order to do so, we wrap the <router-view> tag with a dynamic component <component> tag.
A new src/layouts/LayoutDefault.vue component now renders the layout for us and it provides a default <slot> for the content. This is basically the layout for all the regular pages (views) of our application.
I ended up setting a variable on my index.html
and importing it to the router. This can also be done by importing a variable from a module js file, but setting it on the html
seems to avoid build issues. Simpler solution than I thought, thanks @lamelemon.
// index.html
var serializedModel = @Html.Raw(Model.Serialized());
// router/index.js
var baseUrl = serializedModel.BaseUrl;
export default new VueRouter({
base: baseUrl,
mode: 'history',
routes: [{...}]
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With