首页 > 解决方案 > 如何从 vue js 中的组件渲染组件

问题描述

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

    <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,而是根据 item.type 值用新的 url 覆盖当前组件。

存储组件.vue

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

标签: javascriptvue.jsvuejs2vue-componentvue-router

解决方案


您可以使用动态组件并将其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>


推荐阅读