将空 Laravel 模型值作为道具传递时,Vue 抛出错误

sen*_*nty 2 model laravel vue.js vuejs2

我试图将一个对象称为道具。Auth::user()->car是我的汽车模型,但它可以为空。

现在,在 vue 中,我试图将它传递给我的组件:

<my-comp :car="{{ Auth::user()->car }}"> </my-comp>
Run Code Online (Sandbox Code Playgroud)

如果 Car 对象存在,它就可以工作。但是,如果为null,则vue会抛出错误

[Vue 警告]:无法生成渲染函数:

SyntaxError: Unexpected token } in

我知道我可以$car使用返回return view()->with(..,但是我很好奇为什么这种方法不起作用以及我做错了什么。


我试过的其他方法:

<my-comp :car="{{ Auth::user()->car ? Auth::user()->car : null }}"> </my-comp>

<my-comp car="{{ Auth::user()->car }}"> </my-comp>
Run Code Online (Sandbox Code Playgroud)

Leo*_*ent 6

如果您使用空字符串,模板将无法编译。

你没有设置一个空字符串<my-comp :car=""></my-comp>

正确的方法是:<my-comp :car="''"></my-comp>

回想一下,v-bind需要 javascript 表达式。

所以你可以尝试:

<my-comp :car="{{ Auth::user()->car ? Auth::user()->car : 'null' }}"> </my-comp>
Run Code Online (Sandbox Code Playgroud)

然后你可以在 vue 中解码那个空字符串