2

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>. 
1
  • Can you include the code you tried as well i.e. with the @click and the script? Commented Jan 3, 2017 at 19:17

1 Answer 1

2

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!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.