Vue.js组件表单发送空值

时间:2018-11-15 23:29:16

标签: vue.js ruby-on-rails-5

模型是实体。没有引发任何错误。提交表单并保存一个新的实体。但是,描述和标题都记录为“ nil”。到这里是src/components/NewEntity.vue

<template>
  <div class="entities">
    <h1>Add Entity</h1>
      <div class="form">
        <div>
          <input type="text" name="title" placeholder="TITLE" v-model="title">
        </div>
        <div>
          <textarea rows="15" cols="15" placeholder="DESCRIPTION" v-model="description"></textarea>
        </div>
        <div>
          <button class="app_entity_btn" @click="addEntity">Add</button>
        </div>
      </div>
  </div>
</template>

<script>
import EntitiesService from '@/services/EntitiesService'
export default {
  name: 'NewEntity',
  data () {
    return {
      title: '',
      description: ''
    }
  },
  methods: {
    async addEntity () {
      await EntitiesService.addEntity({
        title: this.title,
        description: this.description
      })
      this.$router.push({ name: 'Entities' })
    }
  }
}
</script>

这是脚本从中导入的位置(出于某种原因,SO最初不允许我包含Services / Api.js):

services/EntitiesServices:

import Api from '@/services/Api'

export default {
  fetchEntities () {
    return Api().get('/entities')
  },

  addEntity (params) {
    return Api().post('entities', {
      title: params.title,
      description: this.description
    })
  }

services/Api.js:

import axios from 'axios'

export default() => {
  return axios.create({
    baseURL: 'http://localhost:3000',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Access-Control-Allow-Origin': '*'
    }
  })
}

1 个答案:

答案 0 :(得分:0)

OG Solutioncperez

根据服务器的不同,您需要通过两种可能的方式在发布函数中 'stringify' 如果您的服务器接受JSON,则:

return Api().post('entities', 
    JSON.stringify({
        title: params.title,
        description: this.description
    })
)

如果服务器不接受JSON,则必须使用querystring module将对象转换为编码的URL参数:

var qs = require('querystring');

return Api().post('entities', 
    qs.stringify({
        title: params.title,
        description: this.description
    })
)