Use Netlify form functionality in Vue applications

Foreword

Netlify with built form-handling capabilities, can be used to store the form data download csv file, and can send e-mail notification upon receiving the transmission request, or by arranging webhook new submission.
It is by parsing the HTML file to identify the html form tag directly when deploying applications to achieve, and how to use paper records in a form functionality Vue applications.

Develop

The first to use @ vue / cli after Vue create a new application, complete a series of steps, running applications

vue create my-awesome-app
...
yarn serve
复制代码

Create a form 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>
复制代码

Note that the root of the application must be retained id = '' app "attribute, otherwise after a static event binding on the page will fail

Listen submit event on the form tag, and prevent the browser default event, use axios request submitted 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("提交失败");
    });
}
复制代码

Install pre-rendered plug  prerender-spa-plugin github.com/chrisvfritz... , the role of static application Vue, Vue applications must be pre-rendered, because if it is rendered by js page, Netlify is not resolved form of the form

yarn add prerender-spa-plugin --dev
复制代码

Create a new vue.config.js file extension used to  webpack configure

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: ['/']
        })
      ]
    }
  }
}

复制代码

The complete code is as follows

<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>

复制代码

deploy

New on a Github repository, upload the code, then click New site form Git on Netlify, authorization, authorization after the completion of the project you want to deploy the warehouse

Fill build command, click the button Deploy site


After a period of waiting, not surprisingly successful application deployed Address

Note must be submitted in a form-name attribute data, otherwise Netlify not receive the data, it returns a 404 error

Input test data, click submit, you can see data in Netlify site operator panel

reference

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

Guess you like

Origin blog.csdn.net/weixin_34137799/article/details/91363069