如何在vue js中从组件渲染组件

问题描述 投票:1回答:1

我有一个包含以下模板的组件:

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

我有另一个名为'StoreComponent'的组件点击第一个组件中的元素我想清除当前组件并显示StoreComponent并能够将item.type传递给StoreComponent。

我不想使用router-link或router.push,因为我不想创建新的url,而是使用新的url覆盖当前组件,具体取决于item.type值。

StoreComponent.vue

     export default{
        name: 'StoreComponent',
        props: ['item'],
        data: function () {
          return {
             datum: this.item
           }
        },
       methods: {
          //custom methods
       }
    }
javascript vue.js vuejs2 vue-component vue-router
1个回答
2
投票

你可以使用dynamic components并传递item-type作为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>
© www.soinside.com 2019 - 2024. All rights reserved.