vue.js

すでに入力されたフォームに対してVue.jsを使う

バリデーションエラーなどで
フォーム入力画面に戻ってきた時など

var data = (function() {
  var $ = function(value) {
    return document.querySelectorAll(value);
  };
  var data = {};

  var inputsSelector = ["text", "date", "email", "color", "month", "number", "search:", "tel", "time", "rul", "week"]
    .map(function(item) {
      return 'input[type="' + item + '"][name]';
    })
    .join(", ");
  var inputs = $(inputsSelector);
  [].forEach.call(inputs, function(input) {
    var result = input.getAttribute("name").match(/\[(\d*)\]$/);
    var name = input.getAttribute("name").replace(/\[\d*\]$/, "");
    var value = input.getAttribute("value");
    var index;
    if (result !== null) {
      index = result[1];
      if (!Array.isArray(data[name])) {
        data[name] = [];
      }
      data[name][index] = value;
    } else {
      data[name] = value;
    }
    input.removeAttribute("value");
  });

  var textareas = $("textarea[name]");
  [].forEach.call(textareas, function(textarea) {
    var name = textarea.getAttribute("name");
    var value = textarea.value;
    data[name] = value;
    textarea.value = "";
    textarea.innerHTML = "";
  });

  var checkboxs = $('input[type="checkbox"][name]');
  [].forEach.call(checkboxs, function(checkbox) {
    var name = checkbox.getAttribute("name").replace(/\[\d*\]$/, "");
    var isChecked = checkbox.hasAttribute("checked");
    if (!Array.isArray(data[name])) {
      data[name] = [];
    }
    if (isChecked) {
      data[name].push(checkbox.getAttribute("value"));
      checkbox.removeAttribute("checked");
    }
  });

  var radios = $('input[type="radio"][name]');
  [].forEach.call(radios, function(radio) {
    var name = radio.getAttribute("name");
    var isChecked = radio.hasAttribute("checked");
    if (!data.hasOwnProperty(name)) {
      data[name] = null;
    }
    if (isChecked) {
      data[name] = radio.getAttribute("value");
      radio.removeAttribute("checked");
    }
  });

  var selects = $("select[name]:not([multiple])");
  [].forEach.call(selects, function(select) {
    var name = select.getAttribute("name");
    var option = select.querySelectorAll("option[selected]");
    var isSelected = option.length > 0;
    if (!data.hasOwnProperty(name)) {
      data[name] = null;
    }
    if (isSelected) {
      data[name] = option[0].getAttribute("value");
      option[0].removeAttribute("selected");
    }
  });

  return JSON.parse(JSON.stringify(data));
})();

var vm = new Vue({
  el: "#form",
  data: data
});