Question: vue.js 2.0 load component dynamically in laravel 5.3

Question

vue.js 2.0 load component dynamically in laravel 5.3

Answers 1
Added at 2017-01-03 17:01
Tags
Question

Is it possible to load a component dynamically when clicking a list item in vuejs 2.0 and laravel 5.3? I have a standard Laravel app but on one section of the site (shows reports) I want to turn this page into a single page application using vuejs. I load the default report in using a vue component and all works well, like so:

        <div class="col-md-3 col-sm-6">
            <div class="card-box">
                <h2>Reports</h2><br>
                <ul>
                    <li>Daily</li>
                    <li>Weekly</li>
                    <li>Season</li>
                    <li>Label</li>
                    <li></li>
                </ul>
            </div>
        </div>
        <div class="col-md-9 col-sm-6">
            <div class="card-box main">
                <reports-homepage></reports-homepage>
            </div>
        </div>

What I'm trying to achieve is when one of the li items is clicked the <reports-homepage></reports-homepage> is changed dynamically according to which li is pressed. So it could become <reports-daily></reports-daily> for example.

I've tried putting a @click on the li component and catching that in a script below in the blade section but that gives me the following error:

[Vue warn]: Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as <script>. 
Answers
nr: #1 dodano: 2017-01-03 23:01

As pointed in the official documentation you can use dynamic components. In your case it could look something like this:

HTML

<div id="app">
    <div class="col-md-3 col-sm-6">
        <div class="card-box">
            <h2>Reports</h2><br>
            <ul>
                <li @click="setComponent('daily')">Daily</li>
                <li @click="setComponent('weekly')">Weekly</li>
                <li @click="setComponent('season')">Season</li>
                <li @click="setComponent('label')">Label</li>
            </ul>
        </div>
    </div>
    <div class="col-md-9 col-sm-6">
        <div class="card-box main">
            <component v-bind:is="currentComponent"></component>
        </div>
    </div>
</div>

JS

var vm = new Vue({
  el: '#app',
  data: {
    currentComponent: 'daily'
  },
  components: {
    'daily': { /* component object */ },
    'weekly': { /* component object */ },
    'season': { /* component object */ },
    'label': { /* component object */ }
  },
  methods: {
    setComponent: function (component) {
        this.currentComponent = component;
    }
  }
})

And that should do what you are trying to achieve. Let me know if it helped!

Source Show
◀ Wstecz