delineas
4/30/2018 - 5:14 PM

Vue – Mailchimp Subscribe Component

Vue – Mailchimp Subscribe Component

/*
 * decaffeinate suggestions:
 * DS102: Remove unnecessary code created because of implicit returns
 * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
 */
// To get the `action` prop:
//
// 1. Go to your dashboard on mailchimp.com and navigate 
//    to Lists > Signup Forms > Embedded Forms.
//
// 2. Copy the `<form>` action from the generated HTML code.
//
// 3. Pass that into the component via the prop, like so:
//
//      <mailchimp-subscribe 
//          action="//yourname.us10.list-manage.com/subscribe/post?u=012345678910&id=ab12345
//      ></mailchimp subscribe>
//

module.exports = {
  name: "MailchimpSubscribe",

  props: {
    action: {
      required: true,
      type: String
    }
  },

  data() {
    return {
      email: '',
      response: {},
      errorMessage: null,
      successMessage: null
    };
  },

  ready() {
    // We need to receive jsonp from Mailchimp. So we update the 
    // action string.
    return this.action = this.action.replace('/post?', '/post-json?').concat('&c=?');
  },

  methods: {
    subscribe(e) {
      const params = $(e.currentTarget).serialize();

      return $.ajax({
        type: 'POST',
        url: this.action,
        data: params,
        dataType: 'jsonp',
        success: res => {
          if (res.result === 'success') {
            return this.successMessage = res.msg;
          } else {
            this.errorMessage = res.msg;
            
            // Mailchimp returns error messages prefixed with numbers (ie "0 - Message"), so we'll
            // strip that out for the end user.
            return this.errorMessage = this.errorMessage.substring(this.errorMessage.indexOf('-')+1, this.errorMessage.length);
          }
        }
      });
    }
  },

  template: `\
<form v-if="!successMessage" @submit.prevent="subscribe($event)">
  <input v-model="email" name="EMAIL" type="text" placeholder="Email" id="email" />
  <input type="submit" />
</form>
<p v-if="errorMessage && !successMessage" transition="fade">{{ errorMessage }}</p>
<p v-if="successMessage" transition="fade">{{ successMessage }}</p>\
`
};