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

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.

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

How to redirect to a specific page of Vue-app via Flask

I'm building an app that has a page which ends in '#' provides some meta info for the page without '#', for example if the page '/user/aabb' has info about the user 'aabb', then the page '/user/aabb#' is the meta page for that user.
The problem is, '/aabb' part doesn't really exist because the app is SPA. 'aabb' is simply delivered as a prop for the component used in '/user' routing. Nor I can directly access '/user/aabb#' in the same context.
So is there a way for Flask to render a specific page of a Vue-build app? so that if the user enters '/user/aabb' on the address bar it links into '/user' page with 'aabb' prop. If there is, I guess the following functionalities should be required.
Flask to redirect to a specific page inside of Vue-route.
Flask to send data to the vue-component of that page.
Vue to receive the data from Flask.
Or is there any other ways to solve this... issue?
Thanks in advance.
The solution to all your questions is to use Vue Router with HTML5 History Mode.
As I mentioned in your last question, set up your Flask app to use the Vue SPA as the front-end
#app.route('/', defaults={'path': ''})
#app.route('/<path:path>')
def catch_all(path):
return app.send_static_file("index.html")
Then set up a router for your front-end URLs
// router.js
import Router from "vue-router"
import Vue from "vue"
Vue.use(Router)
export default new Router({
base: "/", // this should match the root path for your app
mode: "history",
routes: [{
name: "UserMeta",
path: "/user/:username#",
component: () => import("./path/to/UserMeta.vue"),
props: true
}, {
name: "User",
path: "/user/:username",
component: () => import("./path/to/User.vue"),
props: true
}]
})
You have to make the #-suffixed meta routes are listed before the normal pages in order to guarantee it doesn't think the username ends in #. See Matching Priority.
In the example above, both components receive the username route parameter as a prop.
You can then use one of the Data Fetching methods to load data into your components from your Flask API when your routes are loaded.
For example, using Fetching After Navigation and assuming you have a Flask app route for /api/user/<username>...
<template>
<div>
<div v-if="user">
<!-- show user details here -->
</div>
<div v-else>Loading...</div>
<//div>
</template>
<script>
export default {
name: "User",
props: { username: String },
data: () => ({ user: null }),
async created () {
const res = await fetch(`/api/user/${encodeURIComponent(this.username)}`)
this.user = await res.json()
}
}
</script>

Vue.js Router-Link Params Undefined

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"
>

Browser navigation not loading component in Vue.js app

I'm building a single-page application in Vue.js. Currently, navigation through the site works properly until you attempt to use the browser navigation buttons (back/forward).
When attempting to navigate with these no pages will be created. The URL will change but no components are loaded, unless you backup to the base URL where the component is loaded.
The templates are not loaded at all, I also have ESlint which shows no errors.
Here is my index.js for the router:
Vue.use(Router);
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'search',
component: Search,
},
{
path: '/results?terms=:terms',
name: 'results',
component: Results,
},
{
path: '/review?id=:id',
name: 'review',
component: Review,
},
],
});
I change pages by using: this.$router.push({ name: 'results', params: { terms: this.terms } });
I'm very new to Vue so I'm pretty sure I've just made a stupid mistake, but I've spent way too much time trying to figure this out so some help would be nice. Thanks.
The issue here is that route params should not be passed as query string parameters. They are solely intended for use in the URL path.
For some reason, the router is able to handle programmatic navigation but not direct URL loading.
If you still want to use the query string (as opposed to path parameters), I suggest you change to something like this...
Define props for your components, eg
export default {
name: 'Results',
props: ['terms'],
// etc
Pass the query string variables as props in your route definition
{
name: 'results',
path: '/results',
component: Results,
props: route => ({ terms: route.query.terms })
}
Set query instead of params in your programmatic navigation
this.$router.push({ name: 'results', query: { terms: this.terms } })

Angular 6: How to use multiple loadChildren with same route?

I have something like:
const routes: Routes = [
{
path: ':path', component: SiteRoot, children: [
{ path: '', loadChildren: '../modules/maple/template.module#TemplateModule' }
]
}
];
I wish to use this :path url to match multiple module dynamically. each module have there own internal Route.
Is there any way I can achieve this?
I tried ViewContainerRef with ResolveComponentFactory but it does not work with module only component. Event with NgModuleFactoryLoader, Routes cannot be applied.
EDIT, to make everything clear:
What I am trying to achieve is to have different module display on same route path. For example user can see user dashboard at "home" path, and admin can see admin dashboard at "home" path as well.
This feature is defined by business logic, so, I cannot change admin dashboard to another url
I think you are trying to create your routing module incorrectly. Anyway, you should write why you need this. I'll try to answer. Every module should have it's own path, so routing module should be strict and static. If you trying it for security, use guards and hide item from menu component.
If you need URLs like this: "/username1/profile", "/username2/profile" you can simply use code like yours, or use lazy loading. create routing file for parent module:
{ path: ':username', loadChildren: '../users/user.module#UserModule' }
Than create routing file for child module:
{ path: '', loadChildren: 'UserComponent', children: [
{ path: '', redirectTo: 'profile' },
{ path: 'profile', component: ProfileComponent}
]
}
Updated By your case:
by your case you can change your HTML file. For example in app.component.html if your code is:
<div>
<router-outlet></router-outlet>
</div>
You can change it with:
<div *ngIf="isLoggedIn | async">
<admin-panel></admin-panel>
</div>
<div *ngIf="(!isLoggedIn | async)">
<router-outlet></router-outlet>
</div>

Categories

Resources