Netlify 帶有內置表單處理功能,可以用來存儲表單數據,下載 csv 文件,同時可以在接收到新的提交時發送郵件通知或者通過配置 webhook 發送請求。
它是通過在部署應用時直接解析 HTML 文件,識別 html 中的 form 標簽來實現的,本文記錄如何在一個 Vue 應用中使用表單功能。
開發
首先使用@vue/cli 新建一個 Vue 應用,完成一系列步驟后,運行應用
vue create my-awesome-app...yarn serve
創建一個 form 表單
<!-- 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" 屬性,否則經過靜態化之后頁面上綁定的事件會失效
在 form 標簽上監聽 submit 事件,并且阻止瀏覽器默認事件,使用 axios 提交 post 請求
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 表單的
yarn add prerender-spa-plugin --dev
新建一個 vue.config.js 文件用來擴展 webpack 配置
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: ['/'] }) ] } }}完整代碼如下
<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>
新聞熱點
疑難解答
圖片精選