javascript - 如何从 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
}
}
解决方案
您可以使用动态组件并将其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>
推荐阅读
- java - 错误:无法获取 ProductFlavor_Decorated 的未知属性“FabricApiKey”
- c - 将元素添加到有序链接列表
- kotlin-coroutines - 如何过滤 Kotlin Flow 中的列表
- colors - Monaco-Editor:仅激活某些行进行编辑
- android - java.lang.RuntimeException: 使用 EditText (number) 启动 Fragment 时调用观察者方法失败 双向数据绑定
- laravel - Laravel Inertia,带有谷歌登录的 CORS
- android - 使用参数查询 ROOM 数据库后无法让 ViewModel 显示数据(Kotlin)
- ruby-on-rails - 使用提交的哈希安装 gem
- android - 使用 MVP 和 Databinding 从片段中绑定 onclick 方法
- aws-appsync - AppSync WebSocket 连接生命周期