vue js 如何从组件渲染组件
how to render component from a component in 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 值上。
StoreComponent.vue
export default{
name: 'StoreComponent',
props: ['item'],
data: function () {
return {
datum: this.item
}
},
methods: {
//custom methods
}
}
您可以使用 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>
我有一个具有以下模板的组件:
<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 值上。
StoreComponent.vue
export default{
name: 'StoreComponent',
props: ['item'],
data: function () {
return {
datum: this.item
}
},
methods: {
//custom methods
}
}
您可以使用 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>