【问题标题】:How to use Laravel Blade syntax inside vuejs directives?如何在 vuejs 指令中使用 Laravel Blade 语法?
【发布时间】:2021-10-13 22:52:19
【问题描述】:

我刚开始学习 vuejs,我正在尝试将它整合到我的 laravel 项目中,但我遇到了问题。我的 vue 对象中有一组图像路径,如下所示:

 new Vue({
        el: '#app',

        data: {
            images: [
                "img/image-1.png",
                "img/image-2.png",
                "img/image-3.png"   
            ]
        }
    });

我想使用 Laravel 的asset() 帮助器遍历所有图像并在我的页面中显示它们。我试过这样使用它:

<img v-for="image in images" :src="{{ asset('image') }}">

但它不识别 vue 指令:

[Vue warn]: Error compiling template:

invalid expression: Unexpected token ':' in

http://127.0.0.1:8000/image

Raw expression: :src="http://127.0.0.1:8000/image"

【问题讨论】:

  • 试试不带':'的src
  • 那只是忽略vue变量,路径变成src="127.0.0.1:8000/image"
  • 你不能使用资产助手来处理 vue 数据,因为 laravel 先渲染而 vue 在客户端渲染,所以这是不可能的。相反,您可以尝试使用基本网址 :src="'{{ url()-&gt;to('/') }}/'+image"

标签: laravel vue.js laravel-blade


【解决方案1】:

我认为您需要尝试像以下方式迭代循环:

<div v-for="image in images">
    <img :src="image" class="" />
</div>

assets helper 需要以下代码:

<img  src=""  :src="'{{ asset('yourfilepath') }}' +  '/' + image">

希望对你有帮助

【讨论】:

  • 这确实有效,但有人告诉我使用asset() 助手。我会把它标记为正确的,但你可能知道何时以及为什么应该使用 laravel 助手?文档没有对此进行扩展。
【解决方案2】:

您可以转义 VueJS 数据绑定语法,以便同时使用 Blade 和 Vue:

这里是答案,更多详情请阅读:https://stackoverflow.com/a/37934125/9453309

<div>
  <!-- HTML rendering with VueJS -->
  @{{ selectedQuestionDesc }} 
  <!-- Data binding with VueJS -->
  @{{ selectedQuestionDesc }}
</div>
<div>
  <!-- HTML with Laravel Blade -->
  {!! $selectedQuestionDesc !!}
  <!-- Variable binding with Laravel Blade -->
  {{ $selectedQuestionDesc }} 
</div>

【讨论】:

  • 正如我想象的那样,你想让我做&lt;img v-for="image in images" src="{{ asset('@{{ image }}') }}"&gt;,但这会引发错误Unclosed '(' does not match '}'
  • @Nutenn 不行,你需要用双感叹号&lt;img v-for="image in images" :src="{{!! asset('image') !!}}"&gt;
  • 这只会引发类似的错误:[Vue warn]: Error compiling template: invalid expression: Unexpected token '}' in {http://127.0.0.1:8000/image} Raw expression: :src="{http://127.0.0.1:8000/image}"
  • @Nutenn 糟糕,我多放了一个 {},删除一个再试一次,应该是 {!! !!}
猜你喜欢
  • 2020-08-18
  • 2015-09-07
  • 2020-05-26
  • 1970-01-01
  • 2020-07-18
  • 2016-10-22
  • 2021-08-15
  • 1970-01-01
相关资源
最近更新 更多