nuxt1迁移奥nuxt2

我爱Vue(I Love Vue)

I love Vue.js. It’s a fantastic JavaScript framework — easily outclassing in my mind the other offerings — which is saying something because I think they are cool too. And yeah, they do some things better than Vue. Some of them have done things before Vue and Vue adopted it later. But even so, there are solid reasons for preferring Vue.

我喜欢Vue.js。 这是一个很棒JavaScript框架-在我看来很容易超越其他产品-之所以这么说是因为我认为它们也很酷。 是的,他们在某些方面做得比Vue好。 他们中有些人Vue和Vue后来采用它之前做过一些事情。 但是即使如此,还是有充分的理由选择Vue。

Just to run through them quickly:

只是为了快速浏览它们:

  1. Vue has a great learning curve.Vue的学习曲线很好。
  2. It encourages incremental adoption into legacy projects.它鼓励逐步采用旧项目。
  3. Development is driven by community needs.发展是由社区需求驱动的。
  4. Vue maintainers have friendly relationships with other framework maintainers, allowing for a free exchange of ideas and concepts.Vue维护者与其他框架维护者有着友好的关系,从而可以自由交流思想和概念。

也许有些事情可能会更好 (Maybe Some Things Could be Better)

There are more points to make here but, let me move on to a criticism of Vue.js — depending on the type of application you intend to build, or the size of the application, scaffolding a Vue.js app, even with the CLI can be a chore.

这里还有很多要点,但让我继续对Vue.js提出批评–根据您打算构建的应用程序类型或应用程序的大小,即使使用CLI也要搭建Vue.js应用程序可能会很麻烦。

Also, there are details around creating the Vue app that must be observed — it’s not difficult, but if you intend to use Vuex or Vue router then a small amount of configuration is required before you can spin up a store or expect your routes to work.

另外,关于创建Vue应用程序的详细信息也必须遵守-这并不困难,但是,如果您打算使用Vuex或Vue路由器,则需要进行少量配置,然后才能启动商店或期望路由能够正常工作。

There can be quite a bit of variation in where files are kept as well, whether there is a components folder, or how to do the layouts. Certainly the Vue CLI helps with this when it scaffolds a new project, however for Vue router for example, you’ll need to continue to modify the router index.js in order to keep an accurate record of routes.

文件的保存位置,组件文件夹或布局如何也可能有很大的不同。 当然,当Vue CLI搭建新项目时,它会提供帮助,但是对于Vue路由器,例如,您需要继续修改路由器index.js才能准确记录路由。

It’s small changes, but something that could easily be forgotten as an application continues to grow and change. While it’s true that any application, regardless of language or framework will eventually have a checklist of items that need maintained, we should try as best we can to keep the list small and automate when it makes sense.

这是很小的变化,但是随着应用程序的不断发展和变化,很容易将其遗忘。 的确,任何应用程序,无论使用何种语言或框架,最终都将保留需要检查的项目清单,但我们应尽力将清单保持较小,并在有意义时使其自动化。

输入Nuxt.js。 (Enter Nuxt.js.)

If I’m creating a new Vue project, unless it’s very small, it’s rare when I’ll use the Vue CLI instead of using Nuxt. Nuxt makes everything easy. Routing is already preconfigured out of the box and dynamically determined based on the directory structure. It has easily understood options for determining layout, middleware and components.

如果我要创建一个新的Vue项目,除非它很小,否则很少使用Vue CLI而不是Nuxt。 Nuxt使一切变得简单。 路由已预先配置好,并根据目录结构动态确定。 它很容易理解用于确定布局,中间件和组件的选项。

In fact, you can view the structure of this blog as an example. Here is the GitHub.

实际上,您可以以该博客的结构为例。 这是GitHub 。

Nuxt can fill many roles. In the case of this blog, it’s a git based CMS and static site generator. But I’ve also used it to create a single page application, providing a rich experience for the browser. It can be a universal application, providing prerendered or even server side rendered pages very easily. In fact, to create a server side rendered application instead of a single page application here is the line of configuration from nuxt.config.js:

Nuxt可以担任许多职务。 就此博客而言,它是基于git的CMS和静态网站生成器。 但是我也使用它来创建一个单页应用程序,从而为浏览器提供了丰富的体验。 它可以是通用应用程序,可以非常轻松地提供预渲染甚至服务器端的渲染页面。 实际上,要创建服务器端呈现的应用程序而不是单页应用程序,这里是nuxt.config.js的配置行:

ssr: true, // will be a spa if set to false

It’s difficult to describe how Nuxt can be used without providing an example — so let’s create a Nuxt application together.

在不提供示例的情况下很难描述如何使用Nuxt,因此让我们一起创建一个Nuxt应用程序。

示例应用程序要求 (Example App Requirements)

First, let’s get some requirements.

首先,让我们获得一些要求。

Let’s make this a survey app. It’s for fire hydrant inspectors who are required to periodically inspect fire hydrants (pretty sure this is a fake job). So it has these requirements:

让我们将其作为调查应用程序。 适用于需要定期检查消火栓的消火栓检查员(确信这是虚假的工作)。 因此它具有以下要求:

  1. Requires login of a user.需要用户登录。
  2. Collects data about a fire hydrant as a form. (Hydrant serial number and condition)以表格形式收集有关消火栓的数据。 (消防栓序列号和条件)
  3. Must work offline (fire hydrants aren’t always in proximity to cell towers or WIFI).必须脱机工作(消防栓并不总是靠近手机信号塔或WIFI)。
  4. Must transmit fire hydrant data when connected (or reconnected).连接(或重新连接)时必须传输消防栓数据。
  5. Made to work on mobile or tablet.专为在手机或平板电脑上工作而设计。

Okay great. Let’s make some decisions about the app’s architecture.

好的,太好了。 让我们对应用程序的架构做出一些决定。

It needs a login, so we’ll use Auth0. Auth0 will allow us to integrate with other authentication systems so we can have a support for a variety of fire hydrant inspector companies.

它需要登录,因此我们将使用Auth0。 Auth0将允许我们与其他身份验证系统集成,因此我们可以为各种消防栓检查员公司提供支持。

It needs to have a form, so we’ll use bootstrap to cover that requirement. There are newer, better(?), CSS frameworks available but bootstrap will give us everything we need (and a lot we don’t) with very little work.

它需要一个表格,因此我们将使用引导程序来满足该要求。 有可用的更新更好CSS框架,但是引导程序只需很少的工作就可以为我们提供我们需要的一切(很多我们不需要)。

Hmm, requirements 3, 4, and 5 really point to PWA ( Progressive Web Application). So we’ll make this app a PWA as well.

嗯,需求3、4和5确实指向PWA(渐进式Web应用程序)。 因此,我们也将该应用程序设为PWA。

OK. Now what? Well all of this can be done via Nuxt.

好。 怎么办? 那么所有这些都可以通过Nuxt完成。

在Nuxt中做 (Do It In Nuxt)

For authentication we could use @nuxtjs/auth. This is perfect because it has a built in integration with Auth0. But if I didn’t want to use Auth0, it has built-in support for a handful of other authentication providers, or we can extend it to use any authentication provider we need.

对于身份验证,我们可以使用@ nuxtjs / auth 。 这是完美的,因为它具有与Auth0的内置集成。 但是,如果我不想使用Auth0,则它对少数其他身份验证提供程序具有内置支持,或者我们可以扩展它以使用所需的任何身份验证提供程序。

Nuxtjs/auth has a dependency of @nuxtjs/axios an ajax library — which is perfect since we’ll need that to transmit our form data anyway.

Nuxtjs / auth依赖于@ nuxtjs / axios一个ajax库-这是完美的,因为无论如何我们都需要使用它来传输表单数据。

We’ll also need to create this form. We selected bootstrap, so we’ll use bootstrap-vue which has a handy Nuxt.js module to make all of this easy. Also, bootstrap-vue has a way to specify which bootstrap features we’re using so we can use webpack (which is built into Nuxt) to treeshake out the rest. Great! It’s not a perfect fix for bootstrap’s drawbacks, but it’s something.

我们还需要创建此表单。 我们选择了bootstrap,因此我们将使用bootstrap-vue ,它具有一个方便的Nuxt.js模块,可简化所有操作。 另外,bootstrap-vue可以指定我们正在使用的引导程序功能,因此我们可以使用webpack(内置于Nuxt中)对其余的信息进行树状处理。 大! 对于引导程序的缺点来说,这不是一个完美的解决方法,但这是有的。

Finally, we have this PWA requirement. There is a module for that too. @nuxtjs/pwa looks to have everything we need. It will handle all of the icon and manifest stuff, and allow us to easily register a service worker and determine what routes and behavior should be used when a user is offline.

最后,我们有此PWA要求。 也有一个模块。 @ nuxtjs / pwa似乎拥有我们需要的一切。 它将处理所有图标和清单内容,并使我们能够轻松注册服务工作者,并确定用户离线时应使用的路由和行为。

Now, notice all of the things I’m not needing to specify. I don’t need to call up Vue router because that’s already in the mix. Vuex is also in there and it’s a dependency of nuxt/auth, but we may not need it ourselves.

现在,注意我不需要指定的所有内容。 我不需要调用Vue路由器,因为它已经混在一起了。 Vuex也位于其中,它是nuxt / auth的依赖项,但我们自己可能不需要它。

We create the project by running this command:

我们通过运行以下命令来创建项目:

npx create-nuxt-app <project-name>

While this runs it will allow us some options to pull in some of our dependencies. PWA is an option, but an additional npm installation is still required for that. We’ll also be using Axios so that could make more sense to use for now. We can also opt for bootstrap, or a bunch of other CSS frameworks.

在运行时,它将允许我们一些选择来获取一些依赖。 PWA是一个选项,但是仍然需要额外的npm安装。 我们还将使用Axios,因此现在更有意义。 我们还可以选择引导程序或其他一系列CSS框架。

Let’s go ahead and pull in the auth module:

让我们继续并引入auth模块:

npm install @nuxtjs/auth

And, if you haven’t already, make sure to install Axios:

并且,如果尚未安装,请确保安装Axios:

npm install @nuxtjs/axios

and then we modify the nuxt.config.js to add to the modules property:

然后我们修改nuxt.config.js以添加到modules属性:

modules: [  '@nuxtjs/axios',  '@nuxtjs/auth'],auth: {  // Options}

The scaffolding tool also helped us to select a testing tool. I chose Jest.

脚手架工具还帮助我们选择了测试工具。 我选择了杰斯特。

Thanks for the reminder Nuxt! Testing is important. But I will not be talking about testing for this tutorial, sorry.

感谢提醒Nuxt! 测试很重要。 但是,抱歉,我不会谈论测试本教程。

Finally, @nuxtjs/auth reminds us that we need to initialize the Vuex store by adding an index.js file to the store directory. Nuxt will automatically import Vuex and configure it for use when the index.js file is added. (This prevents Vuex being added to projects that don’t need it.)

最后,@ nuxtjs / auth提醒我们,我们需要通过在商店目录中添加index.js文件来初始化Vuex商店。 添加index.js文件时,Nuxt将自动导入Vuex并对其进行配置以供使用。 (这可以防止将Vuex添加到不需要它的项目中。)

Next let’s pull in the PWA module:

接下来,让我们引入PWA模块:

npm install @nuxtjs/pwa

And let’s not forget to set up our manifest!

并且不要忘记设置清单!

pwa: {  manifest: {    name: 'Fire hydrant surveyor',    short_name: 'Hydrant Surveyor',    lang: 'en',    display: 'standalone',  },}

Nuxt PWA is actually 5 different modules in one, only one of which will need some custom code from us.

Nuxt PWA实际上是5个不同的模块,其中只有一个模块需要我们提供一些自定义代码。

  • The icon module — which will configure and make available the icon for the PWA icon.图标模块—将配置PWA图标并使之可用。
  • The meta module — which will set up some some common options for the mobile application.元模块-将为移动应用程序设置一些通用选项。
  • The manifest module — which creates the manifest file with the configured values.清单模块—使用配置的值创建清单文件。
  • The workbox module — which allows setting service workers and cacheable resources — this is where we’ll be doing the bulk of the work for offline behavior.Workbox模块-允许设置服务工作者和可缓存资源-在这里我们将进行大量工作以处理脱机行为。
  • The one signal module — which injects an API which allows for creating push notifications on the mobile device.一个信号模块—注入一个API,该API允许在移动设备上创建推送通知。

Let’s take look at what all of this looks like:

让我们看一下所有这些是什么样的:

Here it is.

在这里。

Just like that we have a functioning application with PWA capabilities, a CSS framework and authentication built in.

就像这样,我们有一个具有PWA功能,内置CSS框架和身份验证的功能正常的应用程序。

At this point we should consider our remaining tasks:

在这一点上,我们应该考虑剩下的任务:

  1. Create an Auth0 account and add the appropriate info to the nuxt config.创建一个Auth0帐户,然后将适当的信息添加到nuxt配置中。
  2. Build the appropriate pages with the auth0 log in and the fire hydrant survey form.使用auth0登录名和消火栓调查表构建适当的页面。
  3. Add cacheable assets to workbox (included from PWA module).将可缓存资产添加到工作箱(包含在PWA模块中)。
  4. Configure and customize the service worker to handle offline workflow.配置和定制服务工作者以处理脱机工作流。

Let’s go for it. Starting with #1.

我们去吧。 从#1开始。

Creating an Auth0 account is super easy. You can log in using GitHub. Auth0 will automatically set up an application for you. You can then grab all of the information you need for the nuxtjs/auth module. You will need to set up a few things in Auth0 Application Settings, such as allowed origins, allowed callback URIs and similar. You can refer to Auth0 documentation on how to do that.

创建Auth0帐户非常简单。 您可以使用GitHub登录。 Auth0将自动为您设置一个应用程序。 然后,您可以获取nuxtjs / auth模块所需的所有信息。 您将需要在Auth0应用程序设置中进行一些设置,例如允许的来源,允许的回调URI等。 您可以参考Auth0文档,了解如何执行此操作。

In nuxt.config.js you’ll need to define the redirect and strategies objects. Note that the callback and login cannot be the same value. The module needs to route to a different page in order to finish processing the user data returned from the login event.

在nuxt.config.js中,您需要定义重定向和策略对象。 请注意,回调和登录名不能相同。 该模块需要路由到其他页面,以完成对从登录事件返回的用户数据的处理。

In nuxt.config.js:

在nuxt.config.js中:

auth: {  redirect: {    login: '/',    callback: options.redirectUri  },  strategies: {    local: false,    auth0: {      domain: options.domain,      client_id: options.client_id,    }  }},

The options object is defined in a separate file: auth_config.js. I did this for my project for convenience, but for a real project I would use a .env file so I could inject the correct values for each environment via the CI/CD pipeline.

options对象在单独的文件auth_config.js中定义。 为了方便起见,我为项目做了此操作,但对于实际项目,我将使用.env文件,以便可以通过CI / CD管道为每个环境注入正确的值。

export const options = {  domain: '...',  client_id: '...',  redirectUri: '/signed-in' //or whatever you configure in Auth0 Application Settings}

While the values contained therein are not secret it is nonetheless recommended that the file not be checked in to source control. You can later modify this file to have an audience property and to change the values based on build environment.

尽管其中包含的值不是秘密的,但是建议不要将文件检入源代码管理。 以后您可以修改此文件以使其具有Audience属性,并根据构建环境更改值。

Next we’ll modify the main route to contain a login button.

接下来,我们将修改主路径以包含一个登录按钮。

<div class="links">  <button    class="button--green"    @click="login"  >    Login  </button></div>

and we’ll define a login method in the Vue instance.

我们将在Vue实例中定义一个登录方法。

export default {  methods: {    login() {      this.$auth.loginWith('auth0')    }  }}

Note: As of this writing there is an issue that requires the installation of an additional npm package.

注意:撰写本文时,存在一个问题,需要安装其他npm软件包。

npm install nanoid@2.1.11

Now when you test this out you should be redirected to an Auth0 login page. Upon successfully signing up or logging in you will be redirected back to the redirect_uri, which in this example project I set as http://localhost:3000.

现在,当您对此进行测试时,应该将您重定向到Auth0登录页面。 成功注册或登录后,您将被重定向回redirect_uri,在本示例项目中,我将其设置为http:// localhost:3000。

Now, let’s further modify the component template so as to display something different once we’re logged in.

现在,让我们进一步修改组件模板,以便在登录后显示不同的内容。

<div class="links">  <b-button    v-if="!$auth.loggedIn"    variant="primary"    size="lg"    @click="login"  >    Login  </b-button>  <b-button    v-else    variant="warning"    @click="logout"    size="lg"  >    Logout  </b-button></div>

Notice we’re starting to switch to using bootstrap-vue components for the buttons. The b-button component accepts a variant and a size prop among other things.

请注意,我们开始切换为对按钮使用bootstrap-vue组件。 b按钮组件可以接受一个变体和一个大小道具。

Now let’s make sure we get the script piece of the page right:

现在,确保我们正确显示了页面的脚本部分:

import { mapGetters } from 'vuex'export default {  methods: {    login() {      this.$auth.loginWith('auth0')    },    logout() {      this.$auth.logout();    }  },  computed: mapGetters(['isAuthenticated']),}

Great! Now with these simple changes we have an application with authentication. So we’ve got #1 and part of #2 done now.

大! 现在,通过这些简单的更改,我们有了一个带有身份验证的应用程序。 因此,我们现在已经完成了#1和#2的一部分。

Here’s the result in GitHub.

这是GitHub中的结果。

The remainder of #2 is to build the survey form. Let’s do that real quick as a component.

#2的其余部分是构建调查表。 让我们真正快速地将其作为一个组件。

Bootstrap-vue makes it all pretty easy. It encompasses the bootstrap classes as components.

Bootstrap-vue使一切变得非常容易。 它包含引导类作为组件。

<template>  <b-container fluid>    <b-form-row>      <b-col sm="3">        <label for="serial-number">Hydrant Serial Number</label>      </b-col>      <b-col sm="9">        <b-form-input          type="text"          v-model="serialNumber"          id="serial-number"          placeholder="Enter the hydrant serial number">        </b-form-input>      </b-col>    </b-form-row>    <b-form-row>      <b-col sm="3">        <label for="condition">Hydrant Condition</label>      </b-col>      <b-col sm="9">        <b-form-select           v-model="condition"           :options="options"           id="condition">        </b-form-select>      </b-col>    </b-form-row>    <b-form-row align-h="end">      <b-col cols="*">        <b-button @click="submit">Submit</b-button>      </b-col>    </b-form-row>  </b-container></template>

Bootstrap-vue took the route of making the grid system into components. I sometimes quibble with that decision, but it is easy to use. In this template, the container (b-container) has a collection of rows (b-row or b-form-row). Each row can have up to 12 columns. Additional columns wrap to the next line. The b-col component can represent any number of columns between 1 and 12. You can then decide how many columns it should take up for each viewport size.

Bootstrap-vue采取了将网格系统变成组件的方法。 我有时会对这个决定表示怀疑,但是它很容易使用。 在此模板中,容器(b容器)具有行(b行或b形式行)的集合。 每行最多可以有12列。 其他列将换行到下一行。 b-col组件可以表示1到12之间的任意数量的列。然后,您可以确定每个视口大小应占用多少列。

For example, you may want bootstrap b-col to take up 12 columns (full width) on mobile so you’d specify cols=”12" as an attribute on the b-col component. But then you might decide it should take up 6 columns (half width) on tablet so you’d specify sm=”6", which is also an attribute. This allows you to declare in the html how a elements should be displayed, in terms of width, on each viewport. Pretty handy!

例如,您可能希望在移动设备上引导b-col占用12列(全宽),因此您可以将cols =“ 12”指定为b-col组件的属性。但是,您可能会决定它应该占用平板电脑上有6列(半宽),因此您要指定sm =“ 6”,这也是一个属性。 这使您可以在html中声明如何在宽度上在每个视口上显示元素。 很方便!

Aside from the fairly decent grid system that bootstrap-vue abstracts for us, there are a number of utility components we can use. In this form, I only need an input, a select, and a button — so I use the bootstrap-vue version of these. Bootstrap has out of the box support for good accessibility on forms and the options on components can remind you of things — like setting a placeholder for example.

除了为我们提供Bootstrap-Vue抽象的相当不错的网格系统之外,我们还可以使用许多实用程序组件。 在这种形式下,我只需要一个输入,一个选择和一个按钮-因此我使用了这些的bootstrap-vue版本。 Bootstrap具有开箱即用的支持,可以很好地访问表单,并且组件上的选项可以使您想起事情-例如设置占位符。

This is a very simple form — we only need a couple of things. We’ll be sending the completed result back to the parent by emitting the result. Here is the script portion of the component:

这是一种非常简单的形式-我们只需要几件事。 我们将通过发出结果将完成的结果发送回父级。 这是组件的脚本部分:

export default {  data() {    return {      serialNumber: "",      condition: null,      options: [       { value: null, text: "Please choose a hydrant condition." },       { value: "poor", text: "Poor" },       { value: "fair", text: "Fair" },       { value: "good", text: "Good" },       { value: "excellent", text: "Excellent" },     ],    };  },  methods: {    submit() {      this.$emit("submit-form", { serialNumber, condition });    },  },};

Now the parent component can handle the result as necessary. Let’s take a look at the parent actually. You know what? Let’s go ahead and refactor that to use bootstrap-vue as well.

现在,父组件可以根据需要处理结果。 让我们看看父母。 你知道吗? 让我们继续进行重构,以便也使用bootstrap-vue。

<template>  <b-container class="pt-5">    <b-row align-h="center" class="mt-5">      <b-col cols="*">        <h1 class="title">Fire Hydrant Surveyor</h1>      </b-col>    </b-row>    <b-row align-h="center" v-if="$auth.loggedIn">      <b-col sm="9" class="my-4">        <survey-form @submitForm="handleFormResult"></survey-form>      </b-col>    </b-row>    <b-row align-h="center" class="mt-3">      <b-col cols="*">        <b-button           v-if="!$auth.loggedIn"           variant="primary"           size="lg"           @click="login">            Login        </b-button>        <b-button           v-else           variant="warning"           @click="logout"           size="lg">            Logout        </b-button>      </b-col>    </b-row>  </b-container></template>

In the parent we’ll also need to import the component and define the handler:

在父级中,我们还需要导入组件并定义处理程序:

import surveyForm from '../components/survey-form'export default {  components: [   surveyForm  ],...  methods: {...    async handleFormResult(formObj) {      //do stuff    }  }...}

Here is the GitHub for this leg of our adventure

这是我们冒险之旅的GitHub

Now we need to figure out what to do with this form data. We’ll be sending the data to our server, but how do we want to do that? Also we’ll need to create the service worker to handle the offline behavior.

现在,我们需要弄清楚如何处理此表单数据。 我们将数据发送到我们的服务器,但是我们要怎么做呢? 同样,我们需要创建服务工作者来处理离线行为。

I found a nice test API someone created so I can send the form data without having to deploy a whole other project, I just needed to massage the data a little bit for it to work.

我发现有人创建了一个不错的测试API,因此我可以发送表单数据而不必部署整个其他项目,我只需要对数据进行一些处理即可。

async handleFormResult(formObj) {  //https://jsonplaceholder.typicode.com/posts is a test API I'm borrowing  //I'm making the data fit because I'm too lazy to make my own test API  const post = {    title: formObj.serialNumber,    body: formObj.condition,    userId: 1   }  try {    const result = await   this.$axios.$post('https://jsonplaceholder.typicode.com/posts', post);    console.log(result);  } catch(e) {    console.log(e);  }}

Okay, so now when I send the request I’m getting a result posted to the console. Everything looks good as long as I’m online.

好的,现在发送请求时,我会将结果发布到控制台。 只要我在线,一切都看起来不错。

But what about when I’m offline?

但是当我离线时呢?

Turns out, all we need is the nuxt/pwa module where workbox will take care of it all for us.

事实证明,我们需要的只是nuxt / pwa模块,Workbox将在其中为我们处理一切。

In order to enable the behavior we want — which is resending failed requests that occur when the app is offline — we need to create a special plugin for workbox.

为了启用我们想要的行为-重发应用程序离线时发生的失败请求-我们需要为工作箱创建一个特殊的插件。

In the plugins folder I created a file called workbox-sync.js and added this code:

在plugins文件夹中,我创建了一个名为workbox-sync.js的文件,并添加了以下代码:

const bgSyncPlugin = new workbox.backgroundSync.BackgroundSyncPlugin('formQueue', {  maxRetentionTime: 24 * 60 // Retry for max of 24 Hours (specified in minutes)});workbox.routing.registerRoute(  /https:\/\/jsonplaceholder\.typicode\.com\/posts/,  new workbox.strategies.NetworkOnly({    plugins: [bgSyncPlugin]  }),  'POST');

We are creating a new background sync plugin and then we’re registering that plugin on a route. The workbox register route method takes 3 arguments, a regex for the route (so you can potentially use a regex to define the same behavior for a range of similar routes), a strategy, and the http verb.

我们正在创建一个新的后台同步插件,然后在路由上注册该插件。 工作箱寄存器路由方法采用3个参数,路由的正则表达式(因此,您可以使用正则表达式为一系列相似的路由定义相同的行为),策略和http谓词。

Next you need to add this plugin to the workbox via these lines of configuration in nuxt.config.js:

接下来,您需要通过nuxt.config.js以下配置行将此插件添加到工作nuxt.config.js

pwa: {  ...  workbox: {    cachingExtensions: '@/plugins/workbox-sync.js',    enabled: true //should be off actually per workbox docs due to complications when used in prod  }}

Note that you cannot do imports in the workbox-sync.js file. The reason is that the plugin is injected into the middle of the sw.js script that the workbox module creates for us. Imports cannot be performed in the middle of a script.

请注意,您无法在workbox-sync.js文件中进行导入。 原因是该插件被注入到工作箱模块为我们创建的sw.js脚本的中间。 导入不能在脚本中间执行。

Also, you’ll have noticed that I have enabled: true but per the @nuxtjs/pwa workbox documentation you should not typically do this since it can cause issues when you are switching between dev and production environments. I do it here because it's so convenient.

此外,您还会注意到我已enabled: true但根据@ nuxtjs / pwa工作箱文档,您通常不应该这样做,因为在开发环境和生产环境之间切换时,这可能会引起问题。 我在这里这样做是因为它非常方便。

Now when I run npm run dev workbox will create the service worker. If I toggle the application to offline via the browser devtools then the posts to the server will fail, but as soon as I switch back to online then the service worker re-sends the requests.

现在,当我运行npm run dev workbox将创建服务工作者。 如果我通过浏览器devtools将应用程序切换为脱机状态,则发布到服务器的操作将失败,但是一旦我切换回联机状态,服务工作人员就会重新发送请求。

Let’s see this in action.

让我们来看看实际情况。

Here we are sending a successful request.

在这里,我们正在发送成功的请求。

But let’s change our status to offline from the dev tools and watch a request fail.

但是,让我们从开发工具将状态更改为脱机,然后观察请求失败。

Now the service worker takes care of re-sending the request. It will use the same information as what was originally sent, so beware if you are using any sort of expiring authentication data. But if we’re reasonable sure the authentication token will remain valid until our users can get back online then this solution will work great.

现在,服务人员负责重新发送请求。 它将使用与最初发送的信息相同的信息,因此请注意,如果您使用的是任何种类的过期身份验证数据。 但是,如果我们有把握地确保身份验证令牌在用户重新联机之前将一直有效,那么该解决方案将非常有用。

If you cannot count on that, then you may need to go with an alternate solution where you keep the data upon a failed request in an indexdb using localforage. Then you would need to create a custom service worker that would need to determine if you are back online and resend the data using the most recent authentication credentials available.

如果您不能依靠它,那么您可能需要使用另一种解决方案,根据失败的请求,使用localforage将数据保留在indexdb中。 然后,您将需要创建一个自定义服务工作程序,该工作程序将需要确定您是否重新联机并使用最新的可用身份验证凭据重新发送数据。

For the final result of our code let’s take a look here.

对于我们代码的最终结果,让我们在这里看看。

We met all of our requirements with very little custom code.

我们只需很少的自定义代码即可满足所有要求。

Now for deployment, Auth0 needs configured to accept my production domain name.

现在进行部署,需要将Auth0配置为接受我的生产域名。

Also, we need to go ahead and refactor out auth.config.js and replace it with .env.

此外,我们需要继续进行重构,以重构auth.config.js并将其替换为.env

I went ahead and did that, first installing cross-env

我继续这样做,首先安装了跨环境

npm install cross-env

Then I created .env file and populated it like so:

然后,我创建了.env文件并将其填充为:

DOMAIN='...auth0.com' CLIENTID='aHashFromAuth0' REDIRECTURI='/signed-in'

I then removed the import of auth.config from nuxt.config and replaced the options with the following:

然后,我从nuxt.config中删除了auth.config的导入,并将选项替换为以下内容:

auth: {  redirect: {    login: '/',    callback: process.env.REDIRECTURI  },  strategies: {    local: false,    auth0: {      domain: process.env.DOMAIN,      client_id: process.env.CLIENTID,    }  }},

Now I can inject the variables via the CI/CD pipeline.

现在,我可以通过CI / CD管道注入变量。

And here is the final result.

这是最终结果。

Nuxt has a huge variety of libraries and plugins that can help you achieve what you’re seeking to do. It’s great to get something off the ground quickly so you can hone in on the business needs.

Nuxt有各种各样的库和插件,可以帮助您实现想要的工作。 Swift取得成功很重要,这样您就可以磨合业务需求。

I hope this is helpful for anyone doing an offline first application!

我希望这对进行离线优先应用程序的任何人都有用!

Originally published at https://www.macivortech.com.

最初在https://www.macivortech.com上发布

翻译自: https://medium.com/@james.macivor1/nuxt-offline-first-pwa-tutorial-782df70b535

nuxt1迁移奥nuxt2


http://www.taodudu.cc/news/show-5745401.html

相关文章:

  • 知识图谱这么火,本文带你揭秘它的前世今生!
  • 大佬开源「抢茅台脚本」,火了
  • 我在奥返火炬进行时卖可乐
  • AQAchain:奥趣链在移动端消费、流通领域中的应用
  • 溜达:蔚县古城 打铁花 观社火
  • 超级玛丽奥项目管理
  • 现在为什么 Python 这么火?
  • GPU及GPU通用计算编程模型简介
  • 低代码行业报告 -- 互联网未来之光
  • 数据分析流程记录
  • 多芯片设计 Designing For Multiple Die
  • C 语言规定 程序中各函数之间( ),C语言规定,程序中各函数之间( )
  • 大学计算机计算思维与网络数字考试,2018秋大学计算机计算思维导论(陇东学院)答案...
  • SAP FUNCTION ALV、SALV开发总结
  • 发现淘宝的一个bug
  • 解决安装流氓软件时,在桌面生成 小游戏 淘宝特卖,以及 Internet 图标的问题。
  • 新手学QT之书籍总结篇
  • 斐波那契之兔子问题解释
  • 关于读书的几个问题
  • Spring相关问题整理
  • 【问题之书】
  • 手把手教你如何用飞桨自动生成二次元人物头像
  • 月薪35k的简历是怎么包装的 ,让面试官心动的标准简历(附模板分享)
  • vscode 打开函数表_vscode函数列表插件
  • python微信聊天机器人,再也不怕被夸情商高了
  • 【译】.NET 7 中的性能改进(八)
  • 【编程实践】编程语言之 Smalltalk
  • 【Python工程师之高性能爬虫】
  • win10安装redis及基本操作
  • 爬虫Day2 获得AJAX包响应

nuxt1迁移奥nuxt2_nuxt离线第一个pwa教程相关推荐

  1. 使用 vue 创建你的第一个 PWA 应用

    本文将介绍使用 VUE3 框架创建 PWA 应用的过程.相关代码 https://github.com/sangyuxiaowu/pwalearn 背景 因为工作上的需要,刚好有跨端和离线缓存的需求, ...

  2. PWA介绍及快速上手搭建一个PWA应用

    PWA初次体验 ​ 前言:本示例不用安装任何东西 部分资源来自网络资源及PWA官网,不要把PWA想象的太复杂,跟着示例走一下,你行的. PWA介绍 一个新的前端技术,PWA( 全称:Progressi ...

  3. PWA入门:手把手教你制作一个PWA应用

    摘要: PWA图文教程 原文:PWA入门:手把手教你制作一个PWA应用 作者:MudOnTire Fundebug经授权转载,版权归原作者所有. 简介 Web前端的同学是否想过学习app开发,以弥补自 ...

  4. 疫情之下,将业务迁移至云端会是一个正确的选择吗?

    突如其来的疫情给所有人的 2020 年都打了一个措手不及,尤其是针对那些业务重点放在线下,且现金流不是特别充裕的企业.这个假期,我们已经听到了太多由于企业现金流紧张而导致倒闭.裁员.降薪等等事件,尤其 ...

  5. linux mysql5.7.36 离线安装使用全教程(含安装包)

    linux mysql5.7.36 离线安装使用全教程(含安装包) 大家好,我是酷酷的韩~ 1.前期准备: mysql版本5.7.36 百度网盘下载地址如下: 内含 mysql-5.7.36-linu ...

  6. junit:junit_简而言之,JUnit:另一个JUnit教程

    junit:junit 为什么还要另一个JUnit教程? 对于Java世界中的开发人员而言, JUnit似乎是最受欢迎的测试工具 . 因此,难怪就此主题已经写了一些好书 . 但是我仍然经常遇到程序员, ...

  7. 简而言之,JUnit:另一个JUnit教程

    为什么还要另一个JUnit教程? 对于Java世界中的开发人员而言, JUnit似乎是最受欢迎的测试工具 . 因此,难怪就此主题已经写了一些好书 . 但是我仍然经常遇到程序员,他们至多对这个工具及其正 ...

  8. 使用ZooKeeper编程 - 一个基本教程

    使用ZooKeeper编程 - 一个基本教程 介绍 障碍 生产者 - 消费者队列 完整的例子 队列测试 屏障测试 来源清单 介绍 在本教程中,我们使用ZooKeeper显示障碍和生产者 - 消费者队列 ...

  9. Linux下Centos7以rpm方式离线安装MySQL5.7教程以及部分报错解决方案

    Linux下Centos7以rpm方式离线安装MySQL5.7教程以及部分报错解决方案 参考文章: (1)Linux下Centos7以rpm方式离线安装MySQL5.7教程以及部分报错解决方案 (2) ...

最新文章

  1. 【TensorFlow2.0】(1) tensor数据类型,类型转换
  2. SpringCloud之Hystrix
  3. HTML内嵌式CSS背景图填充满无截断重复
  4. Faster R-CNN改进篇(二): RFCN ● RON
  5. 查看oracle会话和进程_带有Oracle Digital Assistant和Fn Project的会话式UI。 第三部分,迁移到云...
  6. 以太坊ipfs_动手:Infura和以太坊上的IPFS入门
  7. BPF(BSD Packet Filter)
  8. ADI芯片的通用SPI接口设计
  9. 那些真正有用的经验,都是和高手过招换来的
  10. [导入]【翻译】WF从入门到精通(第二章):workflow运行时
  11. 页眉---header
  12. 央行征信中心:第二代个人征信系统将于1月20日上线
  13. 海思hi3716c机顶盒接usb摄像头和usb无线耳机时,无线耳机有时没有声音
  14. C# Word文档添加水印
  15. 干翻华为才有年终奖,“性感”小米发布MIX3,滑盖全面屏只要3299元
  16. 磁盘阵列 and RAID技术简介
  17. 【机器学习】浅谈 归纳偏置 (Inductive Bias)
  18. win7无线局域网_FAST 讯捷路由器的无线应用
  19. python手写汉字识别_TensorFlow 2.0实践之中文手写字识别
  20. Oracle ERP 库存管理(业务流程 核心流程)

热门文章

  1. Redis 主从配置(带密码)
  2. 多商户商城系统功能拆解38讲-平台端营销-砍价商品
  3. javascript判断数组是否为空
  4. 优秀文章收藏(慢慢消化)持续更新~
  5. datastage mysql wire_DataStage 九、数据交换到MySQL以及乱码问题
  6. 实现中文分词、词性标注、关键词提取、句法分析等智能预处理
  7. docker 常用指令(随心记)
  8. 苹果系统地图定位服务器,iOS 系统地图实现及定位
  9. (个人)健康科技产品要求及标准大集合
  10. 回文树/回文自动机学习