使用Vue,ASP.NET Core和Okta构建安全的待办应用

I love lists. I keep everything I need to do (too many things, usually) in a big to-do list, and the list helps keep me sane throughout the day. It’s like having a second brain!

我喜欢清单。 我将需要做的所有事情(通常有太多事情)保存在一个很大的待办事项列表中,该列表有助于整天保持理智。 就像有第二个大脑!

There are hundreds of to-do apps out there, but today I’ll show you how to build your own from scratch. Why? It’s the perfect exercise for learning a new language or framework! A to-do app is more complex than “Hello World”, but simple enough to build in an afternoon or on the weekend. Building a simple app is a great way to stretch your legs and try a language or framework you haven’t used before.

那里有数百个待办事项应用程序,但是今天我将向您展示如何从头开始构建自己的应用程序。 为什么? 这是学习新语言或框架的完美练习! 待办事项应用程序比“ Hello World”复杂,但足够简单,可以在下午或周末构建。 开发一个简单的应用程序是伸腿并尝试以前从未使用过的语言或框架的好方法。

为什么选择Vue.js和ASP.NET Core? ( Why Vue.js and ASP.NET Core? )

In this article, I’ll show you how to build a lightweight, secure to-do app with a Vue.js frontend and an ASP.NET Core backend. Not familiar with these frameworks? That’s fine! You’ll learn everything as you go. Here’s a short introduction to both:

在本文中,我将向您展示如何使用Vue.js前端和ASP.NET Core后端构建轻便,安全的待办应用程序。 不熟悉这些框架? 没关系! 您将学到一切。 以下是这两者的简短介绍:

Vue.js is a JavaScript framework for building applications that run in the browser. It borrows some good ideas from both Angular and React, and has been gaining popularity recently. I like Vue because it’s easy to pick up and get started. Compared to both Angular and React, the learning curve doesn’t feel as steep. Plus, it has great documentation! For this tutorial, I’ve borrowed from Matt Raible’s excellent article The Lazy Developer’s Guide to Authentication with Vue.js.

Vue.js是一个JavaScript框架,用于构建在浏览器中运行的应用程序。 它借鉴了Angular和React的一些好主意,并且最近已经越来越流行。 我喜欢Vue,因为它很容易上手并开始使用。 与Angular和React相比,学习曲线并不那么陡峭。 另外,它具有出色的文档资料! 在本教程中,我借鉴了Matt Raible的出色文章《懒惰的Vue.js身份验证开发人员指南》 。

ASP.NET Core is Microsoft’s new open-source framework for building web apps and APIs. I like ASP.NET Core on the backend because it’s type-safe, super fast, and has a large ecosystem of packages available. If you want to learn the basics, I wrote a free ebook about version 2.0, which was released earlier this year.

ASP.NET Core是Microsoft的新开源框架,用于构建Web应用程序和API。 我喜欢后端的ASP.NET Core,因为它类型安全,超快并且具有可用的大型软件包生态系统。 如果您想学习基础知识,我写了免费的有关版本2.0的电子书 ,该书于今年早些时候发布。

Ready to build an app? Let’s get started!

准备构建应用程序了吗? 让我们开始吧!

安装工具 ( Install the tools )

You’ll need Node and npm installed for this tutorial, which you can install from the Node.js official site.

本教程需要安装Node和npm,可以从Node.js官方网站进行安装。

You’ll also need dotnet installed, which you can install from the Microsoft .NET site.

您还需要安装dotnet ,可以从Microsoft .NET站点进行安装。

To double check that everything is installed correctly, run these commands in your terminal or shell:

要仔细检查所有内容是否正确安装,请在您的终端或外壳程序中运行以下命令:

npm -v

dotnet --version

使用Vue,ASP.NET Core和Okta构建安全的待办应用_第1张图片

I’m using Visual Studio Code for this project, but you can use whatever code editor you feel comfortable in. If you’re on Windows, you can also use Visual Studio 2017 or later.

我正在为该项目使用Visual Studio Code ,但您可以使用自己喜欢的任何代码编辑器。如果您使用Windows,还可以使用Visual Studio 2017或更高版本。

设置项目 ( Set up the project )

Instead of starting from absolute zero, you can use a template to help you scaffold a basic, working application. Mark Pieszak has an excellent ASP.NET Core Vue SPA starter kit, which we’ll use as a starting point.

您可以使用模板而不是从绝对零开始,以帮助您搭建一个基本的,可运行的应用程序。 Mark Pieszak具有出色的ASP.NET Core Vue SPA入门工具包 ,我们将以此为起点。

Download or clone the project from GitHub, and then open the folder in your code editor.

从GitHub下载或克隆项目,然后在代码编辑器中打开文件夹。

使用Vue,ASP.NET Core和Okta构建安全的待办应用_第2张图片

Run npm install to restore and install all of the JavaScript packages (including Vue.js).

运行npm install还原并安装所有JavaScript软件包(包括Vue.js)。

配置环境并运行应用 (Configure the environment and run the app)

You’ll need to make sure the ASPNETCORE_ENVIRONMENT variable is set on your machine. ASP.NET Core looks at this environment variable to determine whether it’s running in a development or production environment.

您需要确保在ASPNETCORE_ENVIRONMENT上设置了ASPNETCORE_ENVIRONMENT变量。 ASP.NET Core会查看此环境变量,以确定它是在开发环境还是生产环境中运行。

  • If you’re on Windows, use PowerShell to execute $Env:ASPNETCORE_ENVIRONMENT = "Development"

    如果您使用的是Windows,请使用PowerShell执行$Env:ASPNETCORE_ENVIRONMENT = "Development"
  • If you’re on Mac or Linux, execute export ASPNETCORE_ENVIRONMENT=Development

    如果您使用的是Mac或Linux,请执行export ASPNETCORE_ENVIRONMENT=Development

In Visual Studio Code, you can open the Integrated Terminal from the View menu to run the above commands.

在Visual Studio Code中,可以从“查看”菜单中打开“集成终端”以运行上述命令。

Now you’re ready to run the app for the first time! Execute dotnet run in the terminal. After the app compiles, it should report that it’s running on http://localhost:5000:

现在您已经准备好首次运行该应用程序! 在终端执行dotnet run 。 应用编译后,它应报告其正在http:// localhost:5000上运行:

使用Vue,ASP.NET Core和Okta构建安全的待办应用_第3张图片

Open up a browser and navigate to http://localhost:5000:

打开浏览器并导航到http:// localhost:5000 :

使用Vue,ASP.NET Core和Okta构建安全的待办应用_第4张图片

可选:安装Vue Devtools (Optional: Install Vue Devtools)

If Chrome is your preferred browser, I’d highly recommend the Vue Devtools extension. It adds some great debugging and inspection features to Chrome that are super useful when you’re building Vue.js applications.

如果Chrome是您的首选浏览器,则强烈建议您使用Vue Devtools扩展程序。 它为Chrome添加了一些很棒的调试和检查功能,这些功能在构建Vue.js应用程序时非常有用。

生成Vue.js应用 ( Build the Vue.js app )

It’s time to start writing some real code. If dotnet run is still running in your terminal, press Ctrl-C to stop it.

现在该开始编写一些真实的代码了。 如果您的终端仍在运行dotnet run ,请按Ctrl-C停止它。

Delete all the files and folders under the ClientApp folder, and create a new file called boot-app.js:

删除ClientApp文件夹下的所有文件和文件夹,并创建一个名为boot-app.js的新文件:

import Vue from 'vue'
import App from './components/App'
import router from './router'
import store from './store'
import { sync } from 'vuex-router-sync'

// Sync Vue router and the Vuex store
sync(store, router)

new Vue({
  el: '#app',
  store,
  router,
  template: '',
  components: { App }
})

store.dispatch('checkLoggedIn')

This file sets up Vue, and serves as the main entry point (or starting point) for the whole JavaScript application.

该文件设置了Vue,并用作整个JavaScript应用程序的主要入口点(或起点)。

Next, create router.js:

接下来,创建router.js

import Vue from 'vue'
import Router from 'vue-router'
import store from './store'
import Dashboard from './components/Dashboard.vue'
import Login from './components/Login.vue'

Vue.use(Router)

function requireAuth (to, from, next) {
  if (!store.state.loggedIn) {
    next({
      path: '/login',
      query: { redirect: to.path }
    })
  } else {
    next()
  }
}

export default new Router({
  mode: 'history',
  base: __dirname,
  routes: [
    { path: '/', component: Dashboard, beforeEnter: requireAuth },
    { path: '/login', component: Login },
    { path: '/logout',
      async beforeEnter (to, from, next) {
        await store.dispatch('logout')
      }
    }
  ]
})

The Vue router keeps track of what page the user is currently viewing, and handles navigating between pages or sections of your app. This file configures the router with three paths (/, /login, and /logout) and associates each path with a Vue component.

Vue路由器跟踪用户当前正在查看的页面,并处理在应用程序的页面或部分之间的导航。 该文件使用三个路径( //login/logout )配置路由器,并将每个路径与Vue组件相关联。

You might be wondering what store, Dashboard, and Login are. Don’t worry, you’ll add them next!

您可能想知道storeDashboardLogin是什么。 不用担心,接下来您将添加它们!

添加组件 (Add components)

Components are how Vue.js organizes pieces of your application. A component wraps up some functionality, from a simple button or UI element to entire pages and sections. Components can contain HTML, JavaScript, and CSS styles.

Vue.js通过组件来组织应用程序的各个部分。 组件包含一些功能,从简单的按钮或UI元素到整个页面和部分。 组件可以包含HTML,JavaScript和CSS样式。

In the ClientApp folder, create a new folder called components. Inside the new folder, create a file called Dashboard.vue:

在ClientApp文件夹中,创建一个名为components的新文件夹。 在新文件夹中,创建一个名为Dashboard.vue的文件:

<template>
  <div class="dashboard">
    <h2>{{name}}, here's your to-do listh2>

    <input class="new-todo"
        autofocus
        autocomplete="off"
        placeholder="What needs to be done?"
        @keyup.enter="addTodo">

    <ul class="todo-list">
      <todo-item v-for="(todo, index) in todos" :key="index" :item="todo">todo-item>
    ul>

    <p>{{ remaining }} remainingp>
    <router-link to="/logout">Log outrouter-link>
  div>
template>

<script>
import TodoItem from './TodoItem'

export default {
  components: { TodoItem },
  mounted() {
      this.$store.dispatch('getAllTodos')
  },
  computed: {
    name () {
      return this.$store.state.userName
    },
    todos () {
      return this.$store.state.todos
    },
    complete () {
      return this.todos.filter(todo => todo.completed).length
    },
    remaining () {
      return this.todos.filter(todo => !todo.completed).length
    }
  },
  methods: {
    addTodo (e) {
      var text = e.target.value || ''
      text = text.trim()

      if (text.length) {
        this.$store.dispatch('addTodo', { text })
      }

      e.target.value = ''
    },
  }
}
script>

<style>
.new-todo {
  width: 100%;
  font-size: 18px;
  margin-bottom: 15px;
  border-top-width: 0;
  border-left-width: 0;
  border-right-width: 0;
  border-bottom: 1px solid rgba(0, 0, 0, 0.2);
}
style>

The Dashboard component is responsible for displaying all the user’s to-do items, and rendering an input field that lets the user add a new item. In router.js, you told the Vue router to render this component on the / path, or the root route of the application.

仪表板组件负责显示所有用户的待办事项,并渲染一个输入字段,使用户可以添加新项目。 在router.js ,您告诉Vue路由器在/路径或应用程序的根路由上呈现此组件。

This component has HTML in the