Vue.js 将对象作为参数发送到axios-won';行不通

Vue.js 将对象作为参数发送到axios-won';行不通,vue.js,axios,Vue.js,Axios,我正在尝试使用axios在VUE.JS中发送post请求,但出现了一个问题 我在数据中设置了这个测试对象 data () { return { test:{ name: 'foo', surname: 'bar' } }; }, 这是我的方法 testMethod() { axios.post('url',this.test) .then(response => { console.log(response); }) .catch(error => {

我正在尝试使用axios在VUE.JS中发送post请求,但出现了一个问题

我在数据中设置了这个测试对象

data () { return { test:{ name: 'foo', surname: 'bar' } }; },
这是我的方法

testMethod() {

  axios.post('url',this.test)
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  });
}
这行不通。它正在向我的API发送一个空对象。如果我试试这个,它会起作用

testMethod(){

  axios.post('url',{'name':'foo', 'surname': 'bar'})
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  });
}
知道怎么了吗


不确定这是否是错误。

问题在于变量的范围,您使用的是“this”一词,但其值取决于调用的位置。 声明一个变量以确保引用所需的对象

methods: {
  testMethod() {
    //Ensure that you are referring to the Vue Object
    var vm = this;
    axios.post('url',vm.test)
    .then(response => {
      console.log(response);
    })
    .catch(error => {
      console.log(error);
    });
  }
}

可能是同一个问题:@M.suurl,我想不是,伙计。通过查看我的response.request,我可以看到它确实发送了一个空字符串。如果您
console.log(this.test)
就在
axios.post
之前,您会看到正确的数据吗?@patricksteele是的!您的代码中一定有其他内容。这是一个显示Vue组件的axios post的示例,它发送数据时没有问题。