How to setup a netlify form in Nuxt - vue.js

When I navigate to a form using vue-router by adding a link with a <router-link> element, the form does not work. When I hit submit I get a 404 response.
However, if I navigate to it using an <a> tag (triggering a page reload) then it works perfectly.
I suspect that this has to do with the page rendering as a SPA and for some reason not loading an important part of the form for Netlify unless the form page is reloaded? Why is this happening and is there an elegant solution to the problem? I could just replace all links to forms with tags but I'm sure that there is a better solution, I just don't understand the problem well enough to find it.
For context, I am using Nuxt. The forms are recognized by Netlify on the backend and can accept submission with the tag link so that is not the problem.

Since you're using Nuxt, you probably should go SSG/full static with target: 'static' (hostable on Netlify-like platforms) or with target: 'server' (hostable on Heroku-like platforms) but at any point, you should have ssr: true (default value). When you do have this, the biggest part is done.
In Nuxt, you should use <nuxt-link> rather than <router-link>, it works exactly the same (takes the same params etc) but it's more specific to Nuxt and SSR/SSG compatible while <router-link> is not. More details here: https://nuxtjs.org/docs/2.x/features/nuxt-components#the-nuxtlink-component
So, with all of this it should already work great. If it's not, I will gladly help you spot the issue if you have a github repo.
An alternative solution can be to use some form without any SSR dependency like Formspree: https://formspree.io/ (works fine with any SPA)
It works great, really simple. But I'd rather invite you to make a proper SSR form since you're using Nuxt.
PS: use <a> tags only for external links aka the ones which do not start with your domain name, nothing else. A follow of this kind of link is like a hard refresh and should be avoided at all costs.
EDIT: how to deploy by cleaning the cache.
EDIT on how to achieve a working form:
<template>
<div>
<form
netlify
action="/"
method="POST"
name="Contact"
>
<input type="hidden" name="form-name" value="Contact" />
<!-- ... -->
</form>
</div>
</template>
As told in the docs:
[...] inject a hidden input named form-name [...] and the hidden form-name input’s value matches the name attribute of form
Working fine. Could add a honeypot to it to make it even more secure!

Related

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.

nuxt link is updating route, but not changing contents

I am using nuxt version 2.8.1 for my website. Everything works fine, except nuxt-link on some pages.
I have a page, /drinks which is the listing page for drinks and /drinks/{slug} which is the detail page.
I first noticed the problem, in /drinks. None of the nuxt-link was working in that page. It got solved when I removed code that displays
validation error message from the form that is in separate component.
<span class='text-danger small'>{{ errors ? errors.first('name') : '' }}</span>
So, everything works on this page now. But, the detail page still has this problem. There is no components using validation in this page. No erros or warnings, in nuxt console, or browser console. Links just doesn't work. It updates the url, but, contents are not changed at all.
changing nuxt link to anchor tags works.
Another thing is, if I click any drinks in listing page to go to detail page, it works fine. Every link works. But, if I reload that page, or go to that detail page directly with URL, then nuxt link doesn't work.
I don't know, what is the problem exactly. How can, using vee validation in one component affect nuxt link in other components? And why is it not working?
Found the culprit finally. In case, anyone face similiar issue in future.
Vee Validate didn't support ssr, thus, it caused the problem with nuxt-link.
I am using another plugin Vue Carousel which doesn't support SSR as well.
So, wrapping carousel with solved the issue.
And, another weird thing, using v-html with p tag also affected nuxt-link.
So, I removed all p tags with v-html, used no-ssr for components that does not support SSR and the issue is finally gone.
But, I still do not understand why nuxt link is affected and why there are no error messages.

Binding some Vue code to existing, server-side generated HTML

I have an old-style, multiple-page website, with a multiple steps checkout process. This all works with JS disabled, and it is critical that it keeps doing so.
The checkout form has no JS at all, at the moment, and I'd like to improve it progressively (eg. dynamically showing or hiding fields, doing live validation, etc...).
I have already wrapped the entire website with an #app div, and I mounted a Vue instance to it. Then I created a few components which work correctly (but are not critical, so if JS is disabled then the whole thing keeps working and the components are just empty).
Now I have a long checkout form which is generated server-side (say: <form id='address-form'>).
The best course would be to put it into a component (say <checkout-form>) and use it. I can't do this, because 1) the form is generated server-side 2) it needs to work without JS.
Ideally, I would love to create a component with no template, and attach it to the existing HTML.
Is this even possible?
Edit: continuing to dig the Internet, I found this tutorial. This is exactly my problem, but if this is the only way to do it, then I will revert to JQuery :) Manually duplicating the entire HTML (one server side, the other in Vue) is definitely not a good idea.

Is there a recommended way to have all the HTML pre-loaded for SEO purposes while using VueJS, without using SSR?

As the title implies, I need solid SEO and thus I need to have all the HTML loaded on my site on initial load. However, because the backend is written in PHP, and because it would be more work to write my Vue components with the server in mind, I don't want to use server-side rendering (SSR).
That leaves me with the option to send HTML over the wire, the "old school" way. What I am thinking of doing is writing each page's HTML like normal, but make one of the root html elements a Vue element in order to "upgrade" it. So the initial load downloads the finalized HTML, with all the data (tables, lists, etc already populated), but then after all the scripts are loaded, javascript can take over to make things easier and give a better UI experience. This poses a few questions, however:
Am I limited to a single component, the root? It'd be nice to still have many sub-components that would each have their own state. Perhaps inline templates can be used somehow?
Vue templates have their own templating system, like the mustache braces for displaying variables {{ myVar }}. Will I not be able to use them? The one way I can think of is to create a Vue template (that can be loaded from an external script) that is identical to the part of the HTML that it "takes over". The downside is that I'd have to maintain that component both in the original HTML and in the vue template.
Are there any good examples of what I'm trying to accomplish here?
Edit: I want to clarify that I'm aware I can put in various components here and there throughout the page. This still poses the question of how to make those components already start out rendered. Better yet would be to turn the whole page into Vue, much like an SPA.
I need solid SEO and thus I need to have all the HTML loaded on my site on initial load.
This is not entirely true. Google (80% of search traffic) easily parses SPAs now, so SSR purely for SEO isn't required anymore.
But to answer your question in general, you should check out Laracast's Vue.js series. They go in-depth on how to use PHP with Vue.js (including templating and variables).
I'd ask what it is you want to achieve with Javascript/Vue.js in your page. If everything is already rendered in PHP, does Vue provide a simple UX enhancement or takes over most of the page's heavy lifting (navigation, etc.)? If you have no reactive data and want Vue to simply be a controller for rendered components, then knock yourself out, although it might be approaching an 'overkill' scenario.
Have you looked into Prerender SPA Plugin ( https://github.com/chrisvfritz/prerender-spa-plugin )?
It is offered in the Vue documentation as a viable alternative to server side rendering ( https://v2.vuejs.org/v2/guide/ssr.html#SSR-vs-Prerendering )
Recently I've developed a multi-page application using Vue, here is how i tried to solve the SEO (Maybe this can help you ):
Htmls of header and footer (and other main common components) are packed to the page.html(eg: home.html, search.html).
Script and style are of header and footer imported in page.js(eg: home.js, search.js).
Add div.seo-zone to page.html's div#app, which includes the main SEO data(using some h1,h2,p,div and so on), and add
.seo-zone {
display: none;
}
in your css.
4. Make sure your app's root component's el is '#app'(each page's main content can be a Vue app).
Develop your app as usual.
After Vue rendered, the div.seo-zone will be replaced with your Vue components (although it can not be seen)

Aurelia top level component without routing

Is it possible to add an Aurelia top level component without the router?
The goal is to create a component without the router since my application doesn't need any url based navigation.
From what I can tell Aurelia seems to take you down a path where components are instantiated via routing based on how the component is registered with the router.
Instead I would like to just add markup for the top level component on the main index.html page:
<my-component bind.current="'123456'"></my-component>
I would like define components without a router and only use the templating and data binding capabilities of Aurelia.
Is that possible?
Tried this in index.html (inside the body tag of the default project)
<require from='./dist/my-component'></require>
<my-component></my-component>
But it does not seem to pick it up. Ideally I would like to just define it in markup on a page served from the server since it would enable me to sett attributes dynamically on the elements
<my-component current.bind={{someServerGeneratedId}}></my-component>
In the above I would use a templating framework like mustache to dynamically render the Aurelia when the page is served from the server.
I could wrap the component in another "landing" component, but that makes it hard to benefit from setting things up with server generated bindings.
UPDATE:
Per Rob's response: https://github.com/aurelia/framework/issues/175#issuecomment-126965417
- He is expecting to add the ability to add a root component to the landing page in a future release. I understand there are ways to not use the router, but it still depends on pulling in a partial view during bootstrapping of the application. This does not use the router directly, but conceptually this is really just an implied/convention based client side nav. In the end there is a client side request to pull in the view, which means I can't generate the html dynamically from the initial server response.
Yes you can do this very easily without the router. Just remove the router configuration from your app.js and in app.html remove the router code there as well.
I think the issue you are running in to is that you are specifying the dist folder again in your index.html. You should just reference it like this -
<require from="my-component"></require>
<my-component current.bind="someServerGeneratedId"></my-component>
This will bind up correctly.
I guess you're missunderstanding the route concept here.
At the time of writing, Aurelia's index.html page is your initial page where you put your "loading" stuff and where Aurelia bootstraps the entire app.
So, you can't put a custom component directly on it, but that should not be a problem.
If you don't change any configuration on Aurelia, it will look for your app.html to bootstrap your app, and there you can have anything you want (routes or not, doesn't matter). So, you should put your component there, beside the other tags/components/etc you need.
I've made a plunker without any routing and with a custom component in the app.html, and something simulating what you need.
<template>
<require from='./my-component'></require>
<my-component current.bind="serverGeneratedID"></my-component>
</template>
http://plnkr.co/edit/mLb8Ym638b4V2e9LDp0A?p=preview
If you need anything else, comment here and I'll try to go further.