Laravel Vue表单通过对象传参报错,求解决方案
解决Vue表单数据传递时的SyntaxError问题
这个语法错误的根源很清晰——你在构建axios请求的请求体对象时,键名的写法违反了JavaScript对象字面量的语法规则。
当你直接写user.firstName : this.user.firstName这种形式时,JavaScript解析器会把user.firstName当成一个表达式去解析,而不是把它识别为对象的键名,这就直接触发了"Unexpected token"的语法错误。
你可以通过以下两种方式修复这个问题:
方法一:给带点的键名添加引号
如果后端接口期望接收带点格式的扁平键名(比如把user.firstName作为参数名),你只需要把这些特殊的键名用单引号或双引号包裹起来,让解析器明确它们是字符串类型的键:
export default { props: ['user'], methods: { profile() { axios.put(`/web/me`, { 'user.firstName': this.user.firstName, 'user.lastName': this.user.lastName, 'profile.code': this.user.profile.code, }) .then((e) => { window.location.href = '/profile'; }) .catch((e) => { this.errors = e.response.data.errors; }) }, } }
方法二:使用嵌套对象结构(更推荐)
如果后端接口期望的是嵌套的JSON结构(比如接收一个包含user和profile子对象的参数),那你应该把请求体写成嵌套对象的形式,这也是更符合JSON规范的常规写法:
export default { props: ['user'], methods: { profile() { axios.put(`/web/me`, { user: { firstName: this.user.firstName, lastName: this.user.lastName }, profile: { code: this.user.profile.code } }) .then((e) => { window.location.href = '/profile'; }) .catch((e) => { this.errors = e.response.data.errors; }) }, } }
你可以根据后端接口的实际参数要求选择其中一种方式,通常第二种嵌套结构是后端接收数据时更常见的形式哦。
内容的提问来源于stack exchange,提问作者Jahid Mahmud
相关产品推荐
相关产品推荐

