How can use laravel assets in vue component

18,081

Solution 1

The vue component file has the file ending of .vue, you can't use the blade stuff directly in those files, you need to do following:

Vue component have so called props properties so for example if you create following component:

// TestComponent.vue

<template>
    <div>
        <p :users="users"></p>
    </div>
</template>

<script>
    export default {

        props: ['users'],

        data: () => ({
            // ...
        }),
    }
</script>

You can pass data to the props attributes in this case users, so you can call the component in your blade file and add your users from your server side to the props field like this:

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

For images you need to adept this and add your image source.

Don't forget to init the component in your app.js file

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

Solution 2

You can take a different approach, more in line with the way you use asset in the blade templates.

Inside the head section of the layout create a global reference to the base asset path, something like this

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

Next step is to create a Vue mixin. In my case, a trans.js file with the following content:

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

Make sure you include it after Vue, for example:

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

and then you can use it inside all your Vue components. Your original code would look like this

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

Note the lack of {{ and the addition of : in this case, since it is used as an attribute value.

Solution 3

Blade not running on vue component file(.vue files), If you only use just a image path(<img src=" ">) move to images folder to laravel public directory and then you can directly use the image path

<img src="/images/users/avatar-1.jpg" width="35 px" height="23px">

Otherwise you have to call vue props like this answer

Solution 4

Add a forward slash to the beginning of your image path. files should be laravel public folder

<img src="/admin/images/users/avatar-1.jpg">
Share:
18,081
Mahdi Mirhendi
Author by

Mahdi Mirhendi

Updated on July 07, 2022

Comments

  • Mahdi Mirhendi
    Mahdi Mirhendi almost 2 years

    i using laravel with vue js
    i want to show a image element in vue components but i cant use Laravel blades helpers !

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

    its show me Error

    So How Can I Use Assets Helper in vue components?

  • Ayenew Yihune
    Ayenew Yihune about 2 years
    This is the simplest and direct way for me