【问题标题】:How can use laravel assets in vue component如何在 vue 组件中使用 laravel 资产
【发布时间】:2019-03-05 16:50:19
【问题描述】:

我正在使用 laravel 和 vue js
我尝试在 vue 组件中显示图像元素,但我不能使用 Laravel 刀片助手!

<img src="{{asset('admin/images/users/avatar-1.jpg')}}" width="35 px" height="23px">

它显示错误

那么如何在 vue 组件中使用 Assets Helper?

【问题讨论】:

  • this 答案中提取您需要的内容。

标签: php laravel vue.js balde


【解决方案1】:

您可以采用不同的方法,更符合您在刀片模板中使用 asset 的方式。

在布局的 head 部分中创建对基本资源路径的全局引用,如下所示

<script>
window._asset = '{{ asset('') }}';
</script>

下一步是创建一个 Vue mixin。就我而言,trans.js 文件包含以下内容:

module.exports = {
    methods: {
        asset(path) {
            var base_path = window._asset || '';
            return base_path + path;
        }
    }
}

确保在 Vue 之后包含它,例如:

window.Vue = require('vue');
Vue.mixin(require('./asset'));

然后你可以在你所有的 Vue 组件中使用它。您的原始代码如下所示

<img :src="asset('admin/images/users/avatar-1.jpg')" width="35 px" height="23px">

注意在这种情况下缺少{{ 和添加:,因为它被用作属性值。

【讨论】:

    【解决方案2】:

    vue组件文件的文件结尾是.vue,不能直接在这些文件中使用blade的东西,需要做以下操作:

    Vue 组件具有所谓的 props 属性,例如,如果您创建以下组件:

    // TestComponent.vue
    
    <template>
        <div>
            <p :users="users"></p>
        </div>
    </template>
    
    <script>
        export default {
    
            props: ['users'],
    
            data: () => ({
                // ...
            }),
        }
    </script>
    

    在这种情况下,您可以将数据传递给 props 属性用户,因此您可以调用刀片文件中的组件并将您的用户从服务器端添加到 props 字段,如下所示:

    <test-component :users="{{ $users }}"></test-component>
    

    对于图像,您需要熟练掌握这一点并添加图像源。

    别忘了在你的 app.js 文件中初始化组件

    Vue.component('test-component', require('./components/TestComponent.vue'));
    

    【讨论】:

      【解决方案3】:

      blade 不在 vue 组件文件(.vue 文件)上运行,如果只使用图片路径(&lt;img src=" "&gt;)移动到 images 文件夹到 laravel 公共目录,然后可以直接使用图片路径

      &lt;img src="/images/users/avatar-1.jpg" width="35 px" height="23px"&gt;

      否则你必须调用像this answer这样的vue props

      【讨论】:

        【解决方案4】:

        在图像路径的开头添加正斜杠。 文件应该是 laravel 公用文件夹

        <img src="/admin/images/users/avatar-1.jpg">
        

        【讨论】:

          猜你喜欢
          • 2021-06-23
          • 2022-10-04
          • 2019-05-15
          • 2017-02-16
          • 2018-04-13
          • 2020-12-02
          • 2017-04-28
          • 1970-01-01
          • 2020-10-01
          相关资源
          最近更新 更多