How to properly handle non-existent named route? - vuejs2

I am using the Vue Router in my project. When i link to a route whose name does not exist, so for example:
<router-link :to="{ name: 'test-route' }"> link </router-link>
Vue complains in the console saying:
[vue-router] Route with name 'test-route' does not exist
But nothing happens to the user to indicate that something is wrong. The address bar gets changed to the root route (just /), but without the homepage actually showing, and my router.onError handler (which usually handles trying to navigate to lazy loaded components when you lose connection) doesn't fire in this case.
I want to show on screen that something is wrong, a redirection to my 404 page if nothing else.

My suggestion - don't allow a link to be clickable if it is not valid, you can make a condition inside the v-on directive.
v-on="{ to: <does link exist (access router)> ? { name: 'test-route' } : null}".
Might need some syntax fixing but that's the general idea.

Related

Attempting to hydrate existing `runtime-core.esm-bundler.js` markup error in Nuxt 3

I am currently working on a simple app to store workout routines in Nuxt 3 and Appwrite. The link to the source code is here.
Whenever I try to navigate to the /login or /signup route by clicking the links in the navbar, on the first click the page source is not re-rendered (i.e. I keep seeing the same text Landing Page, and on refreshing the route, I get the 500 server error.
Error
The console logs the following warnings, but I have no idea how to correct them or why are they originating.
Console
Any help as to why this hydration error is generating would be really helpful!
PS:
Most probably the error should be originating from either the /pages/signup.vue,
/pages/login.vue or /components/navbar.vue.
I am using Appwrite to manage the back-end of the web app, and the instructions to setup the same can be found in the README.md. (Though I don't think the error I am facing is related to the same.)
You are trying to access a property of null type. That's why you are getting the error.
<div v-if="error.show" class="error">{{ error.message }}</div>
In the above line, you are trying to access error.show but from the global store, the returned error value is null type.So you are trying to access the show property on a null type and thus getting the error.
There are many solutions to handle this. Either, you can just check it in the computed property, or you can use simply add optional chaining like this
<div v-if="error?.show" class="error">{{ error.message }}</div>

How to get rid of Mismatching childNodes vs. VNodes in NuxtJs [duplicate]

I am using Nuxt.js / Vuejs for my app, and I keep facing this error in different places:
The client-side rendered virtual DOM tree is not matching server-rendered content.
This is likely caused by incorrect HTML markup, for example nesting block-level elements inside <p>, or missing <tbody>.
Bailing hydration and performing full client-side render.
I would like to understand what is the best way to debug this error? Is their a way I can record/get the virtual DOM tree for client and server so I could compare and find where the error lies?
Mine is a large application and manually verifying is difficult.
Partial answer: with Chrome DevTools, you can localize the issue and see exactly what element caused the issue. Do the following (I did that with Nuxt 5.6.0 and Chrome 64.0.3282.186)
Show DevTools in Chrome (F12)
Load the page that causes "the client-side rendered virtual DOM tree..." warning.
Scroll to the warning in DevTools console.
Click at the source location hyperlink of the warning (in my case it was vue.runtime.esm.js:574).
Set a breakpoint there (left-clicking at line number in the source code browser).
Make the same warning to appear again. I'm not saying it is always possible, but in my case I simply reloaded the page. If there are many warnings, you can check the message by moving a mouse over msg variable.
When you found your message and stopped on a breakpoint, look at the call stack. Click one frame down to call to "patch" to open its source. Hover mouse over hydrate function call 4 lines above the execution line in patch. Hyperlink to the source of hydrate would open.
In the hydrate function, move about 15 lines from the start and set a breakpoint where false is returned after assertNodeMatch returned false. Set the breakpoint there and remove all other breakpoints.
Make the same warning to happen again. Now, when breakpoint is hit, execution should stop in the hydrate function. Switch to DevTools console and evaluate elm and then vnode. Here elm seem to be a server-rendered DOM element while vnode is a virtual DOM node. Elm is printed as HTML so you can figure out where the error happened.
For me this error happened cuz get Array list in AsyncData and rendered <tr> tags by v-for, i put v-for codes in <client-only> blocks and problem solved
This error can be really painfull to debug. In order to quickly get the element causing an issue edit node_modules/vue/dist/vue.esm.js and add the following lines :
// Search for this line:
function hydrate (elm, vnode, insertedVnodeQueue, inVPre) {
var i;
var tag = vnode.tag;
var data = vnode.data;
var children = vnode.children;
inVPre = inVPre || (data && data.pre);
vnode.elm = elm;
// Add the following lines:
console.log('elm', elm)
console.log('vnode', vnode)
console.log('inVpre', inVPre)
// ...
You will get in the console the failing node.
There are a lot of ways of fixing this issue, but most of them are not actual fixes, just hacky band-aids. To note a few:
wrap it into <client-only> tags, beware of some important details tho
using a v-show instead of a v-if
trying to hack some lifecycles
etc...
I highly recommend reading this gorgeous article written by Alexander Lichter
https://blog.lichter.io/posts/vue-hydration-error/
He'll explain you that you should diagnose why this happens and fix the actual issue.
Basically each time something is different from what was generated on the server and what is available when done hydrating on the client will cause this error.
Some of which are:
invalid HTML (having a block element inside of a <p>, same goes for an a tag nested into another, etc...)
3rd party scripts messing around with your components
different state on server vs client
any random is risky (new Date() for example)
any page related to authentication
I highly recommend reading the article to understand in Alexandre's own words how to handle this kind of issue. If you're in a hurry you could always use one band-aid fix but try to actually fix the issue for the best performance and to keep the code clean.
I had the same issue as of nuxt version 2.14.0 while implementing vue-particles package. The fix was to surround the tags with no-ssr and it fixed the issue.
EDIT:
Updated variant of the solution (if Nuxt version is above 2.9.0)
<client-only>
<vue-particles>
</vue-particles>
</client-only>
Old solution:
<no-ssr>
<vue-particles>
</vue-particles>
</no-ssr>
Thanks to budden73's answer, I did a little improvement on the debug process.
Open dev tool
click on the warn message, and click on the first line of the warn message, you will be directed to the Sources panel, with a file name vue.runtime.esm.js?xxxx
ctrl+f to search the above file for assertNodeMatch, not the function, but like:
if (process.env.NODE_ENV !== 'production') {
if (!assertNodeMatch(elm, vnode, inVPre)) {
return false
}
}
Add a break point at the line return false
Refresh the page, and the breakpoint will be triggered.
At the right side of the Sources panel, Under Scope->Local, click on the elm element, you will be directed back to the Elements panel.
The above element is the client side rendered element, compare with your code to see the difference.
If you can't find the source of the bug, the brutal way to fix it is using nuxt's <client-only> tag.
Another likely brutal way is described here. Add an isHydrate variable which default is false, set to true in mounted hook, and render the element after the variable set to true.
For Nuxt version above 2.10 it doesn't need to install nothing, just use the default component <client-only> as mentioned https://nuxtjs.org/api/components-client-only/.
Check the previous warning:
In "nuxt": "^2.12.2", You can spot the cause easily from the previous warning.
In my case:
Incorrect
<nuxt-link to="/game42day">
<a>Game For Today</a>
</nuxt-link>
Correct:
<nuxt-link to="/game42day">
Game For Today
</nuxt-link>
If you're rendering a component conditionally with v-if, then you have two options to solve the problem:
The first one is wrapping the element in <no-ssr></no-ssr> tag.
The second approach is replacing v-if with v-show, here is the link to Vue docs.
Turns out, in my case, I had HTML comment tags , which was causing this stupid, annoying error. Took me too long to figure it out but in case it helps someone.
In my case I had to change this:
<v-expansion-panel-header v-text="name" />
to this:
<v-expansion-panel-header>{{ name }}</v-expansion-panel-header>
I also get many errors due to this problem. I list two cases I often encounter, hope can help you.
With vuetify button, when you create a common component, you should use: <v-btn>{{text}}</v-btn>. Example:
<template>
<v-btn
:width="width"
:color="color"
:class="[rounded ? 'rounded-pill' : 'rounded-lg',textColor]"
v-on:click="onClick"
elevation="0"
:outlined="outlined"
:type="type"
:name="name"
:form="form"
:disabled="disabled"
v-bind="$attrs"
>{{ text }}</v-btn>
</template>
Don't use v-html with <p> tag.
Not use: <p v-html='html'></p>.
Use: <div v-html='html'></div>.
Besides, if you use <client-only></client-only>, this problem is definitely solved, but if you need to SEO page or show google ads, it is not good solution.
Ok this is going to sound silly. I tried a bunch of different solutions for about 15 mins such as restarting the server and deleting the .nuxt directory but I was too lazy to use #budden73's big brain solution. What ended up working for me was simply restarting my computer, give it a shot.
What I have found so far from observation is that when you are using third party packages like jQuery (specially), they sometimes inject html tags into the dom. So Vue/Nuxt looses track of the dom tree and starts complaining.
I was having the same problem and after a while I removed all jQuery and replaced jQuery functionality with Vuejs and those error were all gone.
See here for an example of how to deal with integrations (e.g. Google Analytics or FB Pixel) that modify the DOM. Basically create a plugin and exclude from SSR.
https://nuxtjs.org/faq/ga
What about:
extend (config, ctx) {
config.resolve.symlinks = false
}
See this [Vue warn]: The client-side rendered virtual DOM tree is not matching server-rendered content ( Nuxt / Vue / lerna monorepo )
Now that you found the code causing the problem, the first thing you should do is to verify that your markup (possibly coming from an API) is valid. Code like <p><p>Text</p></p> is not valid because a p element doesn’t allow other block elements (like a paragraph tag) inside.
Be aware, that tags are not allowed to have block level elements like <div> or <p> as children. These <span> tags are used default tag for Vue’s transitions though. You can change that though via <Transition tag="div">.
Check if have used any block-level element inside the inline element.
for example: inside , inside
If you have used an HTML table make sure you have used the tag
In my case, I changed my codes from
<p v-html="$md.render(post.content)"></p>
to
<p>{{ $md.render(post.content) }}</p>
In my case this problem was caused by markdownit module, I solved it by changing the html markup used with v-html. I was with <p> at the beginning and I ended with <div>.
I have some <p> in my v-html render (with $md.render()) so take care if you have same problems with different markups.

Problem on manual page refresh due to params passed in the URL

How do you all recommend page reloads (i.e. if a User presses refresh page) when using variables within the URL?
I've generated a site statically with nuxt generate and am hosting it at http://www.wowrares.com/. The site generates links properly and is able to navigate to the zone when clicking on the sidebar nav link, but if I were to manually enter http://www.wowrares.com/zone/Ashenvale, it says Page Not Found
Looks like you've followed a broken link or entered a URL that doesn't exist on this site. with a link back to the homepage.
I have it setup so that the API calls are properly occurring when I click on a zone through the navigation, but I would like the above behavior to work properly so I'm assuming this will have to change.
<v-list-item
v-for="(zone, index) in zones"
:key="index"
nuxt
link
#click="mobsInfo(zone)"
>
<v-list-item-avatar>
<v-img :src="zone.image"></v-img>
</v-list-item-avatar>
<v-list-item-content>
<nuxt-link :to="{ name: 'zone-id', params: { id: zone.name } }">
<v-list-item-title class="grey--text subtitle-2">
{{ zone.name }}
</v-list-item-title>
</nuxt-link>
</v-list-item-content>
</v-list-item>
The method used to alter the state:
async mobsInfo(zone) {
this.$store.commit('setZone', zone)
await this.$store.dispatch('fetchMobs', zone)
}
When you go to the link https://wowrares.com/zone/Ashenvale the backend looks for a specific route, folder, file which is not existing in your case. I assume you have an index.html file under the root. That's why you got that message from the server.
Usually I use React or Angular and not that familiar with Vue but I guess hash router is the one what you are looking for. It helps the app identifying where to go once you copy and paste the link or just refresh the page.
Think about the following example, let's say you have the below link:
https://wowrares.com/#/zone/Ashenvale
Once you go the link then backend will ignore the rest of the URL part after the # character thus the original root html file will be opened where you need you handle the routes.
After a quick research I found a simple hash router for Vue in GitHub. Additionaly you can read further about fragment identifier here.
In Nuxt when you generate static website, it would not have an idea how to generate the dynamic routes, because there is lack of any context for it.
There is a way you can get around this issue, but I don't know if you are going to like it.. In nuxt-config.js there is a special property that handles this named generate and the usage is simple yet could get annoying if you have to do it constantly.
generate: {
routes() {
return [
'/posts/1',
'/posts/2',
'/posts/3',
]
}
}
You will be pleased to hear that there are 2 things that you can do to make your life easier, first you can make an http request to your API and return an array with those paths. Second you can even create a separate js file, where you export an array with those ids, either fetched from http request or written by hand (yikes) and them import it in nuxt-config.js and pass it to the routes() method.

How do i get the active route the correct way?

I'm using the typical Vue Router configuration as shown in their guide. What i want is to show the name of the shown route, outside of the router-view. So i would need to ask the router which route is active.
I've found in the router API that it has a currentRoute property, which i was hoping would give me the active route, and i would read its name, and then i'm fine from there.
To test this, i imported the router like so:
import router from '#/router.js';
Then tried to read the name of the active route:
data: function(){
return {
test: router.currentRoute.name
}
}
And displaying it with {{ test }}.
It seems like it's sort of doing what i wanted it to, but it's super inconsistent and unreliable. I don't get any errors anywhere, and the route name does not show up, and seemingly does not work. But then (sometimes) if i change something in my component's template, like delete an element, or add an element, and Vue hot-reloads my app, the route name appears and continues working. From there, if i refresh, it won't appear again.
What am i doing wrong, and what is the correct way of reading the active route name?
Subquestion
Would it be a good idea to use router.beforeEach for this? Because that seems to work correctly, but it seems like a wrong approach for this...
A route object represents the state of the current active route. It
contains parsed information of the current URL and the route records
matched by the URL.
Reference.
You can access current route object through this.$route;.

Trouble with routing Vue.js 2 and browser history

Faced such a problem - I send data to the props of the /router-link/ tag, when I click on the link, I go to the article, it gets the data, everything works. Well, if you press the "back" button in the browser and then "forward" there will be no articles, there will be empty fields without data. How can this be avoided?
This is link to the article
<h3 class="database-article__title">
<router-link
:to="{name : 'article',params: {
id: item.id ,
type:item.type ,
name: item.name,
text: item.text,
author: item.author,
isFavorite: item.isFavorite
}}"> {{item.name}} </router-link>
</h3>
Little part of article-template.vue
<div class="content-type marketing">
{{$route.params.type}}
</div>
<h3 class="database-article__title">
{{$route.params.name}}
</h3>
<div class="database-article__text">
{{$route.params.text}}
</div>
Once again, the data transfer is good, when you click on the link, everything is displayed. The problem is that when clicking on the buttons in the browser "back" and "forward" - the browser history is not saved.
Does anyone know the solution to the problem, or where i can read how to solve it?
Thanks!
My guess is that your article route does not specify any of those params in its path. When you click the link, vue-router will remember the params object you specified in the <router-link> and will be accessible through $route.params in the article component.
However, when you click the browser back then forward buttons, the transition to the article route did not occur by clicking the <router-link> like it did the first time, and since those params were not included in the route's path, $route.params will be empty.
I'm guessing you're just trying to pass data from one route to another. If you want it to persist across history state changes (i.e. browser back/forward), then either:
The data needs to be included in the URL, either as params (e.g. /article/:id/:type etc, this needs to be specified upfront in the route's path) or in the query string (e.g. /article?id=1&type=foo). This isn't ideal for this situation.
(Recommended) Store the item object in such a way that it can be accessed by any route. Vuex is one way, but this may be overkill.
Realistically your URLs should only need to have the article's ID in it, like this /article/1. All the other stuff like type/name/etc don't belong in the URL. From the ID you should be able to fetch the full article object either from a REST API (XHR request), or obtain it from some in-memory data store abstraction (Vuex or anything else really).