1

I have a component with following template:

    <div v-for:"item in store" v-bind:key="item.type">
       <a>{{item.type}}</a>
    </div>

I have another component called 'StoreComponent' On click of a element in first component I want to clear the current component and show the StoreComponent and able to pass item.type to StoreComponent.

I don't want to use router-link or router.push as I don't want to create a new url but override the current component with the new one depending on the item.type value.

StoreComponent.vue

     export default{
        name: 'StoreComponent',
        props: ['item'],
        data: function () {
          return {
             datum: this.item
           }
        },
       methods: {
          //custom methods
       }
    }

1 Answer 1

3

You could use dynamic components and pass the item-type as a prop.

Vue.component('foo', {
  name: 'foo',
  template: '#foo'
});

Vue.component('bar', {
  name: 'bar',
  template: '#bar',
  props: ['test']
}); 

new Vue({
  el: "#app",
  data: {
    theComponent: 'foo',  // this is the 'name' of the current component
    somethingWeWantToPass: {
        test: 123 // the prop we are passing
    },
  },
  methods: {
    goFoo: function() {
        this.theComponent = 'foo';
    },
    goBar: function() {
        this.theComponent = 'bar';
    },
  }
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
  <button @click="goFoo">Foo</button>
  <button @click="goBar">Bar</button>
  <component :is="theComponent" v-bind="somethingWeWantToPass"></component>
</div>


<template id="foo">
  <div>
    Foo
  </div>
</template>

<template id="bar">
  <div>
    Bar
    <div>This is a prop:  {{ this.test }}</div>
  </div>
</template>

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

3 Comments

So for webpack projects, aren't you supposed to have only one template and script tag in each .vue file?
and the prop to be bind is dynamic depending on the default template like in your case it's foo so data has to be passed from foo based on the current item it is processing.
@developer Yes, only one template per component. So I would have three components. The wrapper that tracks the value of the selected item type and holds the component tag. Then the other two components StoreComponent and the one where you select the item type. Then when you select the item type you need to emit an event back to the wrapping component so its knows and can pass the correct value to the StoreComponent.

Your Answer

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