在 Vue 應用中使用 Netlify 表單功能

前言

Netlify 帶有內置表單處理功能,能夠用來存儲表單數據,下載 csv 文件,同時能夠在接收到新的提交時發送郵件通知或者經過配置 webhook 發送請求。
它是經過在部署應用時直接解析 HTML 文件,識別 html 中的 form 標籤來實現的,本文記錄如何在一個 Vue 應用中使用表單功能。javascript

開發

首先使用 @vue/cli 新建一個 Vue 應用,完成一系列步驟後,運行應用css

vue create my-awesome-app
...
yarn serve
複製代碼

建立一個 form 表單html

<!-- data-netlify="true" 代表使用 form 功能 netlify-honeypot="bot-field" 指定機器人識別字段 -->
<template>
  <form id="app" method="POST" name="contact" data-netlify="true" netlify-honeypot="bot-field" @submit.prevent="handleSubmit" >
    <input name="bot-field" hidden>
    <label for="username">
      用戶名:
      <input type="text" id="username" placeholder="請輸入你的用戶名" name="username" v-model="form.username" >
    </label>
    <label for="email">
      郵箱:
      <input type="email" id="email" placeholder="請輸入你的郵箱" name="email" v-model="form.email">
    </label>
    <button type="submit">Submit</button>
  </form>
</template>
複製代碼

注意應用的根節點必定要保留 id=''app" 屬性,不然通過靜態化以後頁面上綁定的事件會失效vue

在 form 標籤上監聽 submit 事件,而且阻止瀏覽器默認事件,使用 axios 提交 post 請求java

yarn add axios
複製代碼
handleSubmit() {
  axios
    .post(
      "/",
      this.encode({
        "form-name": "contact", // 請求數據必定要加上 form-name 屬性
        ...this.form
      }),
      {
        header: { "Content-Type": "application/x-www-form-urlencoded" }
      }
    )
    .then(() => {
      alert("提交成功");
    })
    .catch(() => {
      alert("提交失敗");
    });
}
複製代碼

安裝預渲染插件  prerender-spa-plugin github.com/chrisvfritz…,做用是靜態化 Vue 應用,必定要預渲染 Vue 應用,由於若是是經過 js 渲染的頁面, Netlify 是解析不到 form 表單的webpack

yarn add prerender-spa-plugin --dev
複製代碼

新建一個 vue.config.js 文件用來擴展 webpack 配置ios

const path = require('path')
const PrerenderSPAPlugin = require('prerender-spa-plugin')

module.exports = {
  configureWebpack: () => {
    if (process.env.NODE_ENV !== 'production') return
    return {
      plugins: [
        new PrerenderSPAPlugin({
          staticDir: path.join(__dirname, 'dist'),
          routes: ['/']
        })
      ]
    }
  }
}

複製代碼

完整代碼以下git

<template>
  <!-- data-netlify="true" 代表使用 form 功能 netlify-honeypot="bot-field" 指定機器人識別字段 -->
  <form id="app" method="POST" name="contact" data-netlify="true" netlify-honeypot="bot-field" @submit.prevent="handleSubmit" >
    <input name="bot-field" hidden>
    <label for="username">
      用戶名:
      <input type="text" id="username" placeholder="請輸入你的用戶名" name="username" v-model="form.username" >
    </label>
    <label for="email">
      郵箱:
      <input type="email" id="email" placeholder="請輸入你的郵箱" name="email" v-model="form.email">
    </label>
    <button type="submit">Submit</button>
  </form>
</template>

<script> import axios from "axios"; export default { name: "app", data() { return { form: { username: "", email: "" } }; }, methods: { encode(data) { return Object.keys(data) .map( key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}` ) .join("&"); }, handleSubmit() { axios .post( "/", this.encode({ "form-name": "contact", ...this.form }), { header: { "Content-Type": "application/x-www-form-urlencoded" } } ) .then(() => { alert("提交成功"); }) .catch(() => { alert("提交失敗"); }); } } }; </script>

<style> #app { font-family: "Avenir", Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } label { display: block; } </style>

複製代碼

部署

在 Github 上新建一個倉庫,上傳代碼,以後在 Netlify 上點擊 New site form Git,進行受權,完成受權後選擇要部署的項目倉庫github

image.png

填寫構建命令,點擊 Deploy site 按鈕
web

image.png

通過一段時間的等待,不出意外應用就部署成功了 地址

image.png

注意在提交數據中必定要有 form-name 屬性,不然 Netlify 會接收不到數據,返回 404 錯誤

image.png

輸入測試數據,點擊提交就能夠在 Netlify 的站點操做面板看到數據了

image.png

參考

www.netlify.com/docs/form-h… www.netlify.com/blog/2018/0…

相關文章
相關標籤/搜索