4

I'm trying to learn Laravel and vue.js and stumbled upon a problem. I have this Laravel model which contains a php method that fetches data from a database and puts into objects which are then put into an array. I would then like to access this array inside a vue.js component, but I dont know how I am supposed to do that.

  1. My Laravel model fetches data from the database and puts into objects in an array
  2. I can print out the array, without using vue, from my index.blade.php like this:

    @foreach ($data['hosts'] as $hostsKey => $hostsValue)
        <ul>
            @foreach ($hostsValue as $hostKey => $hostValue)
                <li>{!!$hostKey!!}: {!!$hostValue!!}</li>  
            @endforeach   
        </ul>
    @endforeach
    
  3. Is it possible to access it inside my vue component by putting this in my index.blade.php instead of the above example?

    <div id="app">
        <hosts></hosts>
    </div>
    

    with the app.js looking something like this:

    Vue.component('host', require('./components/host.vue').default);
    
    const app = new Vue({
        el: '#app'
    });
    

    and my host.vue looking like this:

    <template>
        <div>
            {{ hostData }}
        </div>
    </template>
    
    <script>
        export default {
            data(){
                return{
                    hostData: /* MY PHP VARIABLE HERE */
                }
            }
        }
    </script>
    

Started out trying vue today, so please don't be too hard on me.

2
  • I don't speak vue.js, but the general idea of an SinglePageApplication is, that it (vuejs) fetches data from the server when needed through an api. Commented Feb 10, 2019 at 16:14
  • Okay. Maybe I should set up an api with laravel first and use that with vue Commented Feb 10, 2019 at 16:22

1 Answer 1

6

You could modify your component to receive an array as a prop like :

<template>
    <div>
        {{ hostData }}
    </div>
</template>

<script>
    export default {
       props:['hostData'],
        data(){
            return{

            }
        }
    }
</script>

in blade template pass your $data['hosts'] through host-data prop :


<div id="app">
    <host :host-data="{{ json_encode($data['hosts']) }}"></host>
</div>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.