Vue.js Router-Link Params Undefined - javascript

In my vue.js,
I am using params in my navigation.vue to pass it onto the next page for it to be used for dynamic routing such as the following:
<router-link tag="p"
:to="{name: 'Main', params: {category: link.linkCategory}}"
:key="link.linkCategory">
The following is the part of router index.js:
export default [
{
path: '/origin/:category',
name: 'origin',
component: () => import('#/views/origin/origin.vue'),
props: true,
children: [
{
path: '',
name: 'Main',
props: true,
component: () => import('#/views/origin/Main.vue')
}
So basically I'm passing in the 'category' value as the param for dynamic routing.
However, I get this warning message in my console whenever I try to access through the router-link:
[vue-router] missing param for named route "Main": Expected "category" to be defined
All the linkCategory values are stored in a separate link js file for my convenience
and the routing does get the values when each link is clicked.
The routing of all pages works fine but the console warnings are very annoying...
I know that parameter will be empty before accessing the router-link but I need a way to go around the warnings.
I even tried the 'v-if' method but did not work here.
Please fix my code for the wrong things that I did.

What happens if you change the to attribute to a different format as follows?
<router-link tag="p"
:to="`/origin/${link.linkCategory}`"
:key="link.linkCategory"
>

Related

Vue router fails to load child route

I am trying to set up router in my Vue app. Everything seemed to work fine until i started to try implementing children routes. Now when i try to access child route i get an error message along with some warnings:
What happens when i click on child router-link
My router setup:
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', redirect: '/welcome' },
{
name: 'welcome',
path: '/welcome',
component: WelcomePage
},
{
name:'noteLists',
path: '/noteLists',
component: NoteListLinks,
children: [
{
name:'noteListSheets',
path: ':id',
components: FullNoteSheet
}
]
}
],
linkActiveClass: 'active'
});
All other route links work fine.
The components template where child links are used and rendered looks like that:
<template>
<router-link
:to="setNoteListLink(entry.id)"
:key=entry.id
v-for="entry in notesListEntry"
>
{{entry.name}}
</router-link>
<router-view></router-view>
Function setNoteListLink just creates a links like '/noteList/1'.
The error says that it "Cannot read property 'writeDebug' of undefined" and writeDebug is a method on a component that it tries to load when i click on the route (FullNoteSheet), so i assume there is something wrong with the component and not the router. But component works just fine if i try to load it separately, by jst putting it in App component template.
If you have dealt with such issues and know the solution please let me know.
You have a typo in the noteListSheets route; It should be component: FullNoteSheet not components: FullNoteSheet

Parasails.js and using (Vue Router or virtualPages)

Parasails.js documentation mentions that it does support router and virtualPages, but does not actually specify how to interact with these options.
I am somewhat used to the normal Vue setup, of importing Vue, VueRouter and each individual component directly into the .vue file.
But with parasails.js, I feel that these parameters are expecting objects that are not defined in the documentation, so I'm just guessing at this point.
I have gotten to this point so far:
parasails.registerComponent('mainSearch', {
props: [
'prop1',
'prop2',
],
html5HistoryMode: 'history',
virtualPages: [
{ path: '/foo', component: 'page2' },
],
template: `
<div class="test">
<p>Test</p>
<router-link to="/foo">Foo</router-link>
<router-view />
</div>
`,
beforeMount: function() {
//…
// Attach any initial data from the server.
_.extend(this, SAILS_LOCALS);
},
mounted: async function(){
//…
},
beforeDestroy: function() {
//…
},
});
But I am receiving the error:
TypeError: In the HTML template (during render): Cannot read property 'matched' of undefined
Has anyone successfully used router or virtualPages in parasails.js and can help me out?
Also, my next question is: When passing components to virtualPages, do I just supply the name of another parasails registered component as a string? Or do I have to include that component in the code, and pass it as an object as one would do in VueRouter?
Thanks for any and all help!
EDIT
Using virtualPages on a parasails component apparently will not work.
But adding these properties to a parasails page seems to be the intended usage:
virtualPages: true,
html5HistoryMode: 'history',
virtualPageSlug: undefined,
virtualPagesRegExp: /^\/test\/?([^\/]+)?/,
Now, although I am no longer receiving errors, the <router-view></router-view> element is not being populated with the proper view when the <router-link to="/test/foo/">Foo</router-link> is clicked on the page.
I have added the following route to the project
'/test/foo/' : {
view: 'pages/test'
},
Any clues as to why my router-view is not being updated properly?
I think this documentation requires some serious updates as this is a pure guessing game every step of the way.
You're right, that link you provided does seem like its missing some info on how to set the virtual pages. I dont know much about using just parasails but in Sails v1 this is how I set virtual pages. (I use this mostly to have linkable modals.)
In your page script you define your data:
virtualPages: true,
html5HistoryMode: 'history',
virtualPageSlug: undefined,
virtualPagesRegExp: /^\/foo\/bar\/?([^\/]+)?/,
In your ejs file you can add this to a wrapping div:
v-if="virtualPageSlug === 'new'"
Routes file:
'GET /foo/bar/:virtualPageSlug?': { action: 'foo/view-bar' },

How to define new router?

For this question I am referring to the vuestic-admin template from https://github.com/epicmaxco/vuestic-admin
This template is the most suitable template for me. However, I want to make some changes. To be exactly, I want to add a new page, but dont want this page shown in the sidebar. To do this I need to define new router. My problem is: I dont quite understand how to add new router.
Hier is what I have done:
Firstly, I made a .vue file in components/contact/Contact.vue. Its code:
<template>
<div class="contact">
<div class="row">
<div class="col-md-12">
<p>contact</p>
</div>
</div>
</div>
</template>
<script>
export default { name: 'contact' }
</script>
<style lang="scss"></style>
Secondly, I added a new .js file in store/modules/contact.js. Its code:
import lazyLoading from './lazyLoading'
export default {
name: 'Contact',
path: '/contact',
component: lazyLoading('contact/Contact'),
meta: {
default: false,
title: 'menu.contact',
iconClass: 'vuestic-icon vuestic-icon-extras'
}
}
Thirdly, in the store/modules/menu/index.js file, I changed the state defination by adding pages:
import contact from './contact'
const state = {
pages: [
contact
],
items: [
dashboard,
statistics,
forms,
tables,
ui,
extra,
auth
]
}
Fourthly, in router/index.js file, I made following changes:
export default new Router({
routes: [
...generateRoutesFromMenu(menuModule.state.items),
{path: '*', redirect: { name: getDefaultRoute(menuModule.state.items).name }},
...generateRoutesFromMenu(menuModule.state.pages),
{path: '*', redirect: { name: getDefaultRoute(menuModule.state.pages).name }}
]
})
By compiling the changes above I get the console error: Uncaught TypeError: Cannot read property 'name' of undefined
Based on my knowledge (and my guess) the problem should be in the fourth step.
Could anybody please show me a way out of this problem? Thanks a lot!
Looking at the source here for getDefaultRoute(),
function getDefaultRoute (menu = []) {
let defaultRoute
menu.forEach((item) => {
if (item.meta.default) {
defaultRoute = item
} else if (item.children) {
let defaultChild = item.children.find((i) => i.meta.default)
defaultRoute = defaultChild || defaultRoute
}
})
return defaultRoute
}
I would say that you don't need the line
{path: '*', redirect: { name: getDefaultRoute(menuModule.state.pages).name }}
since for contact you have set default: false and there are no children, which means the function returns null (hence the error message you received).
The framework seems to assume a single list of menu items and one of them to be set as default. But I think your approach should work.
The only potential problem is that it looks like you are changing framework code, which means a bit more work when upgrading to next version of the framework.
A note about upgrading
I just ran the basic install, and looking at the project I have to revise my remark about a potential upgrade problem.
Essentially, this is a template not a framework. The difference is that the installer creates starter code in your project's src folder, which you can freely modify and save to a github repository.
There is no package under node_modules that would overwrite your router changes when you run npm install on your project at a future date.
If epicmaxco create a new version of the template that you wish to use, you would simply create a new project and copy the changes you previously made within src to the new project (perhaps run a diff of the old and new src folders).

How to set data into nuxt.js nuxt-link?

I'm trying to pass data into nuxt-link but nuxt-link is just returning a 404 error when I click on the link. It doesn't seem to be getting and loading the file....
The second 2 links that use :href and hardcoding works
<template>
<h2 class="subtitle"><nuxt-link :to="{path: filePath}" exact>Nuxt View Menu</nuxt-link></h2>
<h2 class="subtitle"><a :href="filePath">Vue View Menu</a></h2>
<h2 class="subtitle">HardCode View Menu</h2>
</template>
<script>
export default {
layout: 'default',
data () {
return {
filePath: 'files/officialMenu.pdf'
}
}
}
</script>
Nuxt uses vue-router by reading off the vue-router documentation you'll be able to achieve what you want.
router-link documentation
Example below
<!-- named route -->
<nuxt-link :to="{ name: 'user', params: { userId: 123 }}">User</nuxt-link>
<!-- with query, resulting in `/register?plan=private` -->
<nuxt-link :to="{ path: 'register', query: { plan: 'private' }}">Register</nuxt-link>
This will be available to your next page in $route object as $route.params or in the url query as seen above.
If you use post way to send data another route in vuejs or nuxtjs.
Here, if route name is = /user
So, you have to write the following nuxt-link
<nuxt-link :to="{ name: 'user', params: { userId: 123 }}">User</nuxt-link>
and for receive data next componet, means on "/user" route you have to write inside created or any other place and check console.
created() {
console.log(this.$route.params)
console.log(this.$route.params.userId)
console.log(this.$nuxt._route.params)
console.log(this.$nuxt._route.params.userId)
}
========================================================
if you use Get way to send data another route in vuejs or nuxtjs.
Here, if route name is = /register
so, you have to write the following nuxt-link
<nuxt-link :to="{ path: 'register', query: { plan: 'private' }}">Register</nuxt-link>
and for receive data next componet, means on "/register" route you have to write inside created or any other place and check console.
created() {
console.log(this.$route.query)
console.log(this.$route.query.plan)
console.log(this.$nuxt._route.query)
console.log(this.$nuxt._route.query.plan)
}
Now, you can use this data anywhere like data, mounted, method etc...
How to define route name?????
Add the following code into "nuxt.config.js" file to add route name.
router: {
base: '/',
extendRoutes(routes, resolve) {
routes.push({
name: 'user',
path: '/user',
component: resolve(__dirname, 'pages/user.vue')
})
}
},
Here,
Name property is the name of route that you want to provide as route name.
In Path property you have to provide route path.
Component property is the component path of that component need to load in this route.

Main app component not able to get params

I have a scenario where the first segment in the url will be a unique identifier. That unique identifier will be used in main routes and in the child routes as well.
Here is how i have defined my routes config
export const routes:RouterConfig = [{
path: ':academy_url',
children: [
{path: '', component: CoursesComponent},
{path: 'courses',
children: [
{path: '', component: CoursesComponent}
]
}
}
];
:academy_url is the param i plan on using in the child components. I can access this param in the child components (CoursesComponent for example), but i do not have for some reason access to it in the main app component.
The params array is empty in the main component when i try observables as well as snapshot.How do i access this param in app component? Right now i have a workaround which depends on a service emitting the param value from child components, but that is very inconvenient as this happens every time a component loads or page refreshed.
I need a more direct approach and i feel that it's either a bug or maybe the main app component is not supposed to have access to entry level params?
Also, i tried to create a plunker but i'm not sure how i make it work in there as it gives me undefined route error for it's plunker url key.

Categories

Resources