将标题{{post.name}}
和图像post.imgAttribution
从平铺组件传递到模态组件的最佳方法是什么,这样两个元素在按下按钮时显示相同的数据?
<div id="root" class= "container">
<hero-component></hero-component>
<div class="tile is-ancestor">
<tile-component v-for="post in posts" :key="post.id">
<template slot="header-title">{{post.name}}</template>
<template slot="content-photo"><img :src= "post.imgAttribution"/> </template>
<template slot="button-modal">
<modal-component v-show="showModal" @close="showModal = false"></modal-component>
<a class="button is-primary" v-on:click="showModal=true">Show Cat</a>
</template>
</tile-component>
</div>
</div>
成分:
var HeroComponent = Vue.component('hero-component', {
template: `
<div>
<section class="hero">
<div class="hero-body">
<div class="container">
<h1 class="title">
Cat Gallery
</h1>
</div>
</div>
</section>
</div>`});
var TileComponent = Vue.component('tile-component', {
template:`
<div>
<div class="tile is-parent">
<article class="tile is-child box">
<p class="title">
<slot name="header-title"></slot>
</p>
<p class="content-photo">
<slot name="content-photo"></slot>
</p>
<slot name="button-modal"></slot>
</article>
</div>
</div>
</div>`});
var ModalComponent = Vue.component('modal', {
template: `
<div>
<div class="modal is-active">
<div class="modal-background"></div>
<div class="modal-card">
<header class="modal-card-head">
<p class="modal-card-title">
<!-- title from tile-component -!>
</p>
<button class="modal-close" @click="$emit('close')" ></button>
</header>
<section class="modal-card-body">
<div class="modal-content">
<p class="image is-4by3">
<!-- image from tile-component -!></p>
</div>
</section>
</div>
</div>
</div>`});
Vue.component('modal-component', ModalComponent);
new Vue({
el: '#root',
data: {
showModal: false,
posts: [],
errors: []
},
component: {
'hero-component': HeroComponent,
'modal-component': ModalComponent,
'tile-component': TileComponent
},
created() {
axios.get('http://localhost:3000/Cat/')
.then(response => this.posts = response.data)
.catch(e => this.error.push(e));
}
});
答案 0 :(得分:1)
你已经在使用插槽,为什么不继续?
var ModalComponent = Vue.component('modal', {
template: `
<div>
<div class="modal is-active">
<div class="modal-background"></div>
<div class="modal-card">
<header class="modal-card-head">
<p class="modal-card-title">
<slot name="title"></slot>
</p>
<button class="modal-close" @click="$emit('close')" ></button>
</header>
<section class="modal-card-body">
<div class="modal-content">
<p class="image is-4by3">
<slot name="image"></slot>
</p>
</div>
</section>
</div>
</div>
</div>
`});
以这种方式传递值。这里我使用了一个标题和一个img元素,但你可以做你想做的事。
<modal-component v-show="showModal" @close="showModal = false">
<h1 slot="title">{{post.name}}</h1>
<img slot="image" :src="post.imgAttribution" alt="" />
</modal-component>