简体   繁体   English

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

[英]how to render component from a component in vue js

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.我有另一个名为“StoreComponent”的组件单击第一个组件中的元素时,我想清除当前组件并显示 StoreComponent 并能够将 item.type 传递给 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.我不想使用 router-link 或 router.push,因为我不想创建一个新的 url,而是根据 item.type 值用新的 url 覆盖当前组件。

StoreComponent.vue存储组件.vue

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

You could use dynamic components and pass the item-type as a prop .您可以使用动态组件并将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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM