Cannot Access Vuejs Functional Component Data Again After Loaded

JavaScript frameworks/libraries such as Vue tin can offer a fantastic user experience when browsing your site. Virtually offer a style of dynamically changing page content without having to send a request to the server each fourth dimension.

Nonetheless, there is an issue with this approach. When initially loading your website, your browser doesn't receive a consummate page to display. Instead, it gets sent a bunch of pieces to construct the folio (HTML, CSS, other files) and instructions for how to put them all together (a JavaScript framework/library) It takes a measurable amount of time to put all this information together before your browser actually has something to brandish. Information technology'south like beingness sent a bunch of books along with a flat-pack bookcase. You'd have to build the bookcase commencement and and so fill it with the books.

The solution to this is clever: Have a version of the framework/library on the server that tin can build a ready-to-brandish folio. Then send this consummate page to the browser along with the ability to brand farther changes and still have dynamic page content (the framework/library), only like existence sent a ready-made bookcase along with some books. Certain, you even so have to put the books in the bookcase, but you've got something usable immediately.

Visual comparison of client-side and server-side rendering

Across the light-headed illustration, there are too a bunch of other advantages. For instance, a folio that rarely changes, such as an Virtually Usa page, doesn't demand to be recreated every single fourth dimension a user asks for it. So a server tin create information technology one time and and then enshroud it or store information technology somewhere for time to come employ. These kinds of speed improvements may seem tiny, just in an environment where time until responsiveness is measured in milliseconds (or less), every little scrap counts.

If you lot'd similar more information on the advantages of SSR in a Vue surroundings, you should check out Vue's own commodity on SSR. At that place is a diverseness of options to achieve these results, just the most popular 1, which is also recommended by the Vue team, is Nuxt.

Why Nuxt.js

Nuxt.js is based off an implementation of SSR for the popular React library called Next. After seeing the advantages of this pattern, a like implementation was designed for Vue called Nuxt. Those familiar with the React+Next combination volition spot a agglomeration of similarities in design and layout of the application. Nevertheless, Nuxt offers Vue-specific features to create a powerful yet flexible SSR solution for Vue.

Nuxt was updated to a product-ready 1.0 version in Jan 2018 and is part of an agile and well-supported customs. I of the slap-up things is that building a project using Nuxt isn't that different from building whatever other Vue project. In fact, it provides a bunch of features that let you to create well-structured codebases in a reduced amount of fourth dimension.

Another of import thing to annotation is Nuxt doesn't have to be used for SSR. It's promoted equally a framework for creating universal Vue.js applications and includes a control (nuxt generate) for creating static generated Vue applications using the aforementioned codebase. So if you're apprehensive about diving deep into SSR, don't panic. You can always create a static site instead while however taking advantage of Nuxt's features.

In order to grasp the potential of Nuxt, let's create a simple project. The final source code for this project is hosted on GitHub if you desire to see information technology, or you can view a live version created using nuxt generate and hosted on Netlify.

Creating a Nuxt Project

To starting time off, let'due south use a Vue project generator called vue-cli to rapidly create a sample project:

          # install vue-cli globally npm install -one thousand vue-cli  # create a project using a nuxt template vue init nuxt-community/starter-template my-nuxt-projection                  

After going through a couple options, this will create a project inside the folder my-nuxt-project or whatsoever you specified. Then we but demand to install dependencies and run the server:

          cd my-nuxt-project npm install # Or yarn npm run dev                  

At that place we get. Open your browser to localhost:3000 and your project should exist running. Not much different from creating a Vue Webpack project. However, when we look at the bodily structure of the app, there's non much there, especially when compared to something similar the Vue Webpack template.

Diagram of project directories and their relation to the Nuxt config file

Looking in the bundle.json likewise shows that we merely have one dependency, Nuxt itself. This is because each version of Nuxt is tailored to work with specific versions of Vue, Vue-router, and Vuex and bundles them all together for you lot.

In that location is also a nuxt.config.js file at the projection root. This allows you to customize a bunch of features that Nuxt provides. By default, information technology sets the header tags, loading bar colour, and ESLint rules for you. If yous're eager to see what you can configure, here's the documentation; we will be covering some options in this article.

And then what'southward so special about those directories?

Project Layout

If you lot browse through the directories created, all of them accept an accompanying Readme stating a cursory summary of what goes in that directory and often a link to the docs.

This is one benefit of using Nuxt: a default structure for your application. Any good front-end developer will structure an application similar to this, just there are many dissimilar ideas about structures, and when working on a team, some fourth dimension will inevitably go into discussing or choosing this construction. Nuxt provides one for you.

Nuxt volition look for sure directories and build your application for you depending on what it finds. Let's examine these directories one by one.

Pages

This is the just required directory. Whatever Vue components in this directory are automatically added to vue-router based on their filenames and the directory structure. This is extremely convenient. Normally I would have a separate Pages directory anyway and take to manually register each of those components in another router file. This router file tin go complex for larger projects and may need splitting to maintain readability. Instead, Nuxt will handle all of this logic for you.

To demonstrate, we can create a Vue component called about.vue inside the Pages directory. Permit's just add a simple template such as:

          <template>  <h1>About Page</h1> </template>                  

When yous relieve, Nuxt volition re-generate the routes for you. Seeing as we called our component about.vue, if you navigate to /about, you should see that component. Simple.

There is i filename which is special. Naming a file index.vue will create a root route for that directory. When the project is generated, there'southward already an alphabetize.vue component in the pages directory which correlates to the homepage or landing page of your site. (In the development example, this would simply be localhost:3000.)

Nuxt scans the Vue files in the pages directory and outputs the appropriate pages.

What about deeper routes? Sub-directories in the Pages directory help to structure your routes. And then if we wanted a View Product page, we could structure our Pages directory something like this:

          /pages --| /products ----| index.vue ----| view.vue                  

Now, if we navigate to /products/view, nosotros volition come across the view.vue component inside the products directory. If we navigate instead to /products, we will run into the index.vue component inside the products directory.

Yous may be request why we didn't merely create a products.vue component in the pages directory instead like we did for the /about page. You lot may think the result would be the aforementioned, but there is a difference between the two structures. Allow's demonstrate this by adding some other new page.

Say we wanted a seperate About page for each employee. For case, let's create an About page for me. Information technology should exist located at /about/ben-jones. Initially, we may try structuring the Pages directory like this:

          /pages --| most.vue --| /about ----| ben-jones.vue                  

When we try to access /about/ben-jones, we instead get the nigh.vue component, the same as /about. What's going on hither?

Interestingly, what Nuxt is doing here is generating a nested route. This structure suggests that you desire a permanent /most route and anything inside that route should be nested in its own view area. In vue-router, this would be signified by specifying a <router-view /> component inside the virtually.vue component. In Nuxt, this is the same concept except, instead of <router-view />, we only utilize <nuxt />. And so let'south update our near.vue component to allow for nested routes:

          <template>  <div>    <h1>About Page</h1>    <nuxt />  </div> </template>                  

At present, when nosotros navigate to /almost, we get the about.vue component we had before, with but a title. Withal, when we navigate to /about/ben-jones, we instead accept the title and the ben-jones.vue component rendered where the <nuxt/> placeholder was.

This wasn't what nosotros initially wanted, merely the idea of having an Well-nigh page with a listing of people that, when clicked on, make full a department on the page with their information is an interesting concept, so permit'southward leave it as is for at present. If y'all did want the other pick, and so all nosotros would do is restructure our directories. Nosotros'd only accept to move the about.vue component inside the /about directory and rename it index.vue, so the resulting structure would be:

          /pages --| /about ----| index.vue ----| ben-jones.vue                  

Finally, say we wanted to use route params to retrieve a specific production. For example, nosotros desire to be able to edit a product by navigating to /products/edit/64 where 64 is the product_id. We can practise this the following manner:

          /pages --| /products ----| /edit ------| _product_id.vue                  

Note the underscore at the showtime of the _product_id.vue component—this signifies a route param which is then accessible on the $route.params object or on the params object in Nuxt'southward Context (more on that later). Annotation that the primal for the param volition exist the component name without the initial underscore—in this case, product_id—so endeavor to keep them unique within the projection. As a result, in _product_id.vue, we may take something like:

          <template>  <h1>Editing Product {{ $route.params.product_id }}</h1> </template>                  

Y'all can offset to imagine more complex layouts, which would be a pain to prepare using vue-router. For example, nosotros tin can combine all of the to a higher place into a road such every bit:

          /pages --| /categories ----| /_category_id ------| products.vue ------| /products --------| _product_id.vue                  

Information technology's not likewise difficult to reason on what /categories/2/products/3 would display. We would have the products.vue component with a nested _product_id.vue component, with two road params: category_id and product_id. This is much simpler to reason on than an equivalent router config.

While we're on the topic, one thing I tend to do in the router config is set router guards. Equally Nuxt is building the router for us, this tin can exist washed instead on the component itself with beforeRouteEnter. If y'all want to validate route params, Nuxt provides a component method called validate. So if you wanted to bank check if the product_id was a number before trying to return the component, you would add the post-obit to the script tag of _product_id.vue:

          consign default {  validate ({ params }) {    // Must exist a number    render /^\d+$/.test(params.product_id)  } }                  

Now, navigating to /categories/two/products/someproduct results in a 404 considering someproduct isn't a valid number.

That's it for the Pages directory. Learning how to structure your routes properly in this directory is essential, so spending a lilliputian time initially is important to getting the virtually out of Nuxt. If you're looking for a cursory overview, it is ever helpful to refer to the docs for routing.

If you're worried about not being in control of the router, don't be. This default setup works great for a wide diversity of projects, provided they are well structured. However, there are some cases where you may need to add together more routes to the router than Nuxt automatically generates for you or restructure them. Nuxt provides a way to customize the router instance in the config, allowing you to add new routes and customize generated routes. You can also edit the core functionality of the router instance, including extra options added by Nuxt. So if you practice encounter an border instance, you still have the flexibility to notice the advisable solution.

Store

Nuxt tin build your Vuex shop based on the structure of the shop directory, similar to the Pages directory. If you don't need a store, just remove the directory. There are two modes for the store, Classic and Modules.

Classic requires you lot to have an index.js file in the store directory. There you lot need to export a function that returns a Vuex instance:

          import Vuex from 'vuex'  const createStore = () => {  return new Vuex.Shop({    state: ...,    mutations: ...,    actions: ...  }) }  export default createStore                  

This allows y'all to create the store nevertheless you lot wish, much like using Vuex in a normal Vue projection.

Modules mode also requires y'all to create an index.js file in the store directory. However, this file only needs to export the root state/mutations/actions for your Vuex store. The example below specifies a bare root state:

          consign const country = () => ({})                  

Then, each file in the store directory will be added to the store in its own namespace or module. For example, let'southward create somewhere to shop the current production. If we create a file called product.js in the store directory, then a namespaced section of the store volition be available at $shop.product. Here'due south a simple instance of what that file may look like:

          export const land = () => ({  _id: 0,  title: 'Unknown',  price: 0 })  export const actions = {  load ({ commit }) {    setTimeout(      commit,      yard,      'update',      { _id: 1, championship: 'Product', price: 99.99 }    )  } }  export const mutations = {  update (state, product) {    Object.assign(state, product)  } }                  

The setTimeout in the load action simulates some sort of API call, which volition update the store with the response; in this instance, information technology takes one second. At present, let's use information technology in the products/view page:

          <template>  <div>    <h1>View Production {{ product._id }}</h1>    <p>{{ product.title }}</p>    <p>Toll: {{ production.price }}</p>  </div> </template>  <script> import { mapState } from 'vuex' consign default {  created () {    this.$store.dispatch('production/load')  },  computed: {    ...mapState(['product'])  } } </script>                  

A few things to note: Here, we are calling our imitation API when the component is created. You tin see that the product/load activity nosotros are dispatching is namespaced under Product. This makes it articulate exactly what department of the store we are dealing with. And then, by mapping the land to a local computed property, nosotros tin easily apply information technology in our template.

There is a problem: We meet the original state for a second while the API runs. Later, we will utilise a solution provided by Nuxt to ready this (known as fetch).

Just to stress this again, we never had to npm install vuex, every bit it is already included in the Nuxt bundle. When you add together an index.js file to the store directory, all those methods are then opened upward to you automatically.

That'due south the main ii directories explained; the rest are much simpler.

Components

The Components directory is at that place to incorporate your reusable components such as a navigation bar, image gallery, pagination, data tables, etc. Seeing every bit components in the Pages directory are converted into routes, you lot need somewhere else to store these types of components. These components are accessible in pages or other components by importing them:

          import ComponentName from ~/components/ComponentName.vue                  

Assets

This contains uncompiled assets and has more to do with how Webpack loads and processes files, rather than with how Nuxt works. If you're interested, I advise reading the guide in the Readme.

Static

This contains static files which are mapped to the root directory of your site. For instance, putting an paradigm chosen logo.png in this directory would make it available at /logo.png. This is skillful for meta files like robots.txt, favicon.ico, and other files you need bachelor.

Layouts

Normally, in a Vue project, you have some sort of root component, normally called App.vue. Here is where you tin set upwardly your (normally static) app layout, which may include a navbar, footer, and and then a content area for your vue-router. The default layout does exactly that and is provided for you in the layouts folder. Initially, all information technology has is a div with a <nuxt /> component (which is equivalent to <router-view />) simply it can be styled however you wish. For example, I've added a simple navbar to the example project for navigation around the various demonstration pages.

A layout can be applied to multiple pages.

You may want to have a different layout for a certain section of your app. Maybe y'all have some sort of CMS or admin console that looks different. To solve this, create a new layout in the Layouts directory. Every bit an example, let'south create an admin-layout.vue layout which merely has an extra header tag and no navbar:

          <template>  <div>    <h1>Admin Layout</h1>    <nuxt />  </div> </template>                  

And so, we can create an admin.vue page in the Pages directory and utilise a property provided past Nuxt called layout to specify the name (as a string) of the layout we want to employ for that component:

          <template>  <h1>Admin Page</h1> </template>  <script> consign default {  layout: 'admin-layout' } </script>                  

That's all there is to it. Page components volition employ the default layout unless specified, but when you navigate to /admin, it now uses the admin-layout.vue layout. Of course, this layout could exist shared beyond several admin screens if you lot wish. The one of import matter to remember is layouts must contain a <nuxt /> element.

There's one final thing to note near layouts. You lot may have noticed while experimenting that if you type an invalid URL, you are shown an mistake page. This fault folio is, in fact, another layout. Nuxt has its own mistake layout (source lawmaking hither), but if you wanted to edit it, simply create an error.vue layout and that will be used instead. The caveat here is that the mistake layout must non have a <nuxt /> element. Y'all will also have access to an error object on the component with some basic information to brandish. (This is printed out in the terminal running Nuxt if you desire to examine information technology.)

Middleware

Middleware are functions that can be executed before rendering a folio or layout. At that place is a variety of reasons you may desire to do so. Road guarding is a pop use where you could bank check the Vuex store for a valid login or validate some params (instead of using the validate method on the component itself). Ane project I worked on recently used middleware to generate dynamic breadcrumbs based on the route and params.

These functions can be asynchronous; just exist careful, as nothing will exist shown to the user until the middleware is resolved. They also accept access to Nuxt'south Context, which I will explicate subsequently.

Plugins

This directory allows y'all to register Vue plugins before the application is created. This allows the plugin to exist shared throughout your app on the Vue instance and exist accessible in whatsoever component.

Most major plugins have a Nuxt version that can be hands registered to the Vue case by following their docs. However, at that place will be circumstances when you will be developing a plugin or demand to conform an existing plugin for this purpose. An example I'm borrowing from the docs shows how to practise this for vue-notifications. Get-go, we need to install the bundle:

          npm install vue-notifications --relieve                  

And so create a file in the plugins directory called vue-notifications.js and include the post-obit:

          import Vue from 'vue' import VueNotifications from 'vue-notifications'  Vue.utilise(VueNotifications)                  

Very similar to how you would register a plugin in a normal Vue environment. Then edit the nuxt.config.js file at your project root and add together the post-obit entry to the module.exports object:

          plugins: ['~/plugins/vue-notifications']                  

That'south information technology. Now you tin can utilize vue-notifications throughout your app. An example of this is at /plugin in the example project.

So that completes a rundown of the directory structure. It may seem a lot to learn, but if you lot're developing a Vue app, you're already setting up the aforementioned kind of logic. Nuxt helps to abstract abroad the setup and help you focus on building.

Nuxt does more than assist in development though. Information technology supercharges your components by providing extra functionality.

Nuxt's Supercharged Components

When I get-go started researching Nuxt, I kept reading almost how Page components are supercharged. It sounded peachy, only it wasn't immediately obvious what exactly that meant and what benefits information technology brings.

What information technology means is that all Page components have extra methods attached to them that Nuxt can use to provide additional functionality. In fact, we've already seen ane of these before when we used the validate method to cheque params and redirect a user if they are invalid.

The two chief ones used in a Nuxt project will exist the asyncData and fetch methods. Both are very similar in concept, they are run asynchronously before the component is generated, and they tin be used to populate the data of a component and the store. They also enable the page to exist fully rendered on the server before sending it to the customer even when nosotros have to await for some database or API call.

What's the difference between asyncData and fetch?

  • asyncData is used to populate the information of the Page component. When you return an object, it is and so merged with the output of data before rendering.
  • fetch is used to populate the Vuex Shop. If yous return a promise, Nuxt volition look until it is resolved before rendering.

So permit'due south put these to expert use. Recall before on the /products/view page we had a problem where the initial state of the store was being displayed briefly while our imitation API call was being made? 1 manner of fixing this is having a boolean stored on the component or in the Store such as loading = true and then displaying a loading component while the API phone call finishes. Afterwards, we would set loading = false and display the data.

Instead, let's use fetch to populate the Shop earlier rendering. In a new folio chosen /products/view-async, let's change the created method to fetch; that should work, right?

          consign default {  fetch () {    // Unfortunately the beneath line throws an error    // because 'this.$store' is undefined...    this.$store.dispatch('product/load')  },  computed: {...} }                  

Here's the catch: These "supercharged" methods run before the component is created, so this doesn't signal to the component and cipher on it can be accessed. So how practise we access the Store hither?

The Context API

Of class, in that location is a solution. On all of Nuxt'southward methods, you are provided with an argument (unremarkably the beginning) containing an extremely useful object called the Context. In this is everything you will need reference to across the app, pregnant we don't need to wait for Vue to create those references on the component offset.

I would highly recommend checking out the Context docs to see what is available. Some handy ones are app, where you tin can access all your plugins, redirect, which can be used to modify routes, error to display the fault page, and some self-explanatory ones such as road, query, and shop.

So, to admission the Store, we tin destructure the Context and excerpt the Shop from it. We also demand to make sure we return a promise and then that Nuxt tin wait for it to resolve before rendering the component, and then nosotros need to make a small adjustment to our Store activity too.

          // Component export default {  fetch ({ store }) {    render store.acceleration('production/load')  },  computed: {...} }  // Store Action load ({ commit }) {  render new Promise(resolve => {    setTimeout(() => {      commit('update', { _id: 1, title: 'Product', cost: 99.99 })      resolve()    }, grand)  }) }                  

You could utilise async/wait or other methods depending on your coding fashion, but the concept is the aforementioned—we're telling Nuxt to make sure the API phone call finishes and the Shop is updated with the result earlier trying the return the component. If y'all try navigating to /products/view-async, you volition not see the wink of content where the product is in its initial state.

You lot tin imagine how useful this can be in any Vue app even without SSR. The Context is also bachelor to all middlewares as well as to other Nuxt methods such equally NuxtServerInit which is a special store action that runs before the Store is initialized (an instance of this is in the next section)

Considerations When Using SSR

I'chiliad sure many (myself included) who start using a technology such as Nuxt while treating it similar any other Vue project somewhen hit a wall where something we know would ordinarily work seems incommunicable in Nuxt. As more of these caveats are documented, it volition be easier to overcome, just the primary thing to consider when starting to debug is that the client and server are two separate entities.

When you access a page initially, a request is sent to Nuxt, the server builds as much as possible of that folio and the residue of the app, and so the server sends it to you. And so the responsibility is on the client to continue with navigation and load chunks as it needs them.

Nosotros want the server to do every bit much as possible kickoff, merely sometimes it doesn't accept admission to the information information technology needs, which results in the work existence done client-side instead. Or worse, when the final content presented by the client is dissimilar from what the server expected, the client is told to rebuild it from scratch. This is a big indication that something is wrong with the awarding logic. Thankfully, an error will be generated in your browser's console (in evolution manner) if this starts to happen.

Permit'southward accept an example of how to solve a mutual issue, session management. Imagine y'all have a Vue app where yous can log in to an account, and your session is stored using a token (JWT, for example) which you decide to keep in localStorage. When you initially access the site, you desire to cosign that token against an API, which returns some basic user info if valid and puts that information in the Store.

After reading through Nuxt's docs, yous run into that in that location's a handy method called NuxtServerInit which allows you to asynchronously populate the Store once on initial load. That sounds perfect! And then you lot create your user module in the Store and add together the advisable action in the index.js file in the Store directory:

          export const actions = {  nuxtServerInit ({ acceleration }) {    // localStorage should work, right?    const token = localStorage.getItem('token')    if (token) return dispatch('user/load', token)  } }                  

When y'all refresh the folio, you go an error, localStorage is non defined. Thinking about where this is happening, it makes sense. This method is run on the server, information technology has no idea what is stored in localStorage on the client; in fact, it doesn't fifty-fifty know what "localStorage" is! So that'due south not an option.

The server tries to execute localStorage.getItem('token') but throws an error, then a caption below explaining the problem.

So what'due south the solution? There are a few, actually. You lot tin can get the customer to initialize the Shop instead but end upwards losing the benefits of SSR considering the client ends upwardly doing all the work. You can set up sessions on the server and then use that to authenticate the user, merely that'southward some other layer to set upwards. What's most similar to the localStorage method is using cookies instead.

Nuxt has access to cookies considering they are sent with the request from the customer to the server. Equally with other Nuxt methods, nuxtServerInit has access to the Context, this time as the 2d argument because the beginning is reserved for the shop. On the Context, we tin access the req object, which stores all the headers and other data from the customer request. (This volition be specially familiar if you've used Node.js.)

Then subsequently storing the token in a cookie instead (called "token," in this case), permit'south access it on the server.

          import Cookie from 'cookie'  consign const actions = {  nuxtServerInit ({ dispatch }, { req }) {    const cookies = Cookie.parse(req.headers.cookie || '')    const token = cookies['token'] || ''    if (token) return dispatch('user/load', token)  } }                  

A simple solution, merely one that might not be immediately obvious. Learning to think almost where certain actions are happening (client, server, or both) and what they take access to takes some time but the benefits are worth it.

Deployment

Deployment with Nuxt is extremely unproblematic. Using the same codebase, you lot can create an SSR app, single-folio awarding, or static page.

Server-side Rendered App (SSR App)

This is probably what you lot were aiming for when using Nuxt. The bones concept for deployment hither is to run the build process on whatever platform you lot choose and set a few configurations. I'll employ the Heroku example from the docs:

Starting time, gear up scripts for Heroku in package.json:

          "scripts": {  "dev": "nuxt",  "build": "nuxt build",  "kickoff": "nuxt start",  "heroku-postbuild": "npm run build" }                  

Then set upwards the Heroku surround using the heroku-cli (setup instructions hither:

          # set Heroku variables heroku config:set NPM_CONFIG_PRODUCTION=false heroku config:gear up HOST=0.0.0.0 heroku config:set NODE_ENV=production  # deploy git button heroku master                  

That'due south it. At present your SSR Vue app is live set for the world to see. Other platforms have different setups, but the process is similar. The official deployment methods currently listed are:

  • At present
  • Dokku (Digital Ocean)
  • Nginx

Single-page Awarding (SPA)

If yous wanted to take advantage of some of the actress features Nuxt provides but avoid the server trying to render pages, then y'all can deploy as an SPA instead.

Kickoff, it's best to test your application without the SSR as by default npm run dev runs with SSR on. To change that, edit the nuxt.config.js file and add the following option:

          mode: 'spa',                  

Now, when you run npm run dev, SSR will be turned off and the application will run as an SPA for yous to test. This setting likewise makes sure no hereafter builds will include SSR.

If everything looks fine, then deployment is exactly the same as for an SSR app. Just remember you need to set mode: 'spa' first to let the build procedure know y'all want an SPA.

Static Pages

If you lot don't want to deal with a server at all and instead want to generate pages for employ with static hosting services such as Surge or Netlify, and so this is the option to cull. Just bear in mind that, without a server, you lot won't exist able to access the req and res in the Context, and then if your code relies on that, exist sure to suit it. For example, when generating the case project, the nuxtServerInit role throws an fault because it's trying to fetch a token from the cookies in the asking headers. In this projection, it doesn't affair, as that data isn't beingness used anywhere, just in a existent awarding, there would demand to be an culling way to access that data.

Once that's sorted, deployment is easy. One thing you will probably need to change first is adding an option then that the nuxt generate command will also create a fallback file. This file volition prompt the hosting service to let Nuxt handle the routing rather than the hosting service, throwing a 404 error. To do so, add the post-obit line to nuxt.config.js:

          generate: { fallback: truthful },                  

Here's an case using Netlify, which isn't currently in the Nuxt docs. Just acquit in heed that if this is your showtime fourth dimension using netlify-cli, yous volition be prompted to authenticate:

          # install netlify-cli globally npm install netlify-cli -m  # generate the application (outputs to dist/ binder) npm run generate  # deploy netlify deploy dist                  

It's every bit simple as that! Equally mentioned at the outset of the commodity, there'southward a version of this project here. In that location's likewise official deployment documentation for the post-obit services below:

  • Surge
  • GitHub Pages

Learn More than

Nuxt is updating quickly, and this is only a small-scale pick of the features it offers. I hope this article encourages yous to try it out and see if it could help meliorate the capabilities of your Vue applications, allowing you lot to develop faster and take reward of its powerful features.

If y'all're looking for more information, then look no farther than Nuxt's official links:

  • Documentation
  • Playground
  • GitHub
  • FAQ

Looking to upward your JavaScript game? Try reading The Comprehensive Guide to JavaScript Design Patterns by fellow Toptaler Marko MiĊĦura.

mickelsenbising.blogspot.com

Source: https://www.toptal.com/vue-js/server-side-rendered-vue-js-using-nuxt-js

0 Response to "Cannot Access Vuejs Functional Component Data Again After Loaded"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel