我需要将数据从组件传递到另一个组件吗?

时间:2019-06-10 07:35:21

标签: vuejs2

我有两个组件(“新闻”组件和“新闻详细信息”组件,我需要将标题,描述和图像从新闻转移到详细页面吗?

**News Component**
<template>
    <div class="container mt-5 mb-5">

    <div class="row">
        <div class="col-md-12">
            <h2 class="text-center mb-3">Our News</h2>
        </div>
        <div class="col-md-4 text-center" v-for="newss in news">
            <img :src="newss.imgSrc" class="img-fluid"  style="width: 300px; height: 300px;">
            <h2>{{newss.title}}</h2>
            <p>{{newss.paragraph}}</p>
            <router-link to="/news-details">
                <button class="btn btn-success"  >Read More</button>
            </router-link>
        </div>
    </div>
    </div>
</template>


<script>
    export default {
        data : function () {
            return{
                news:[
                    {
                        title : 'News One',
                        paragraph : 'News Description One',
                        imgSrc: 'https://www.gstatic.com/webp/gallery/1.jpg'
                    },
                    {
                        title : 'News Two',
                        paragraph : 'News Description Two',
                        imgSrc: 'https://www.gstatic.com/webp/gallery/2.jpg'
                    },
                    {
                        title : 'News Three',
                        paragraph : 'News Description Three',
                        imgSrc: 'https://www.gstatic.com/webp/gallery/3.jpg'
                    }

                ]
            }
        },

     }
</script>


**News Details Component**
<template>
    <div class="container mt-5 mb-5">

        <div class="row">
            <div class="col-md-12">
                <h2 class="text-center mb-3">News Details</h2>
            </div>
            <div class="col-md-4 text-center">
                <img :src="imgSrc" class="img-fluid"  style="width: 300px; height: 300px;">
                <h2>{{title}}</h2>
                <p>{{paragraph}}</p>
            </div>
        </div>
    </div>
</template>


<script>
    export default {
        props: {
            title : String,
            paragraph: String,
            imgSrc: String
        }

    }
</script>

我有两个组件(“新闻”组件和“新闻详细信息”组件,我需要将标题,描述和图像从新闻转移到详细页面吗?

1 个答案:

答案 0 :(得分:0)

通过组件传输内容的方式有多种。

首先 通过$ emit(),您可以捕获父组件中的更改,还可以将带有prop的更改传递给其他子组件。

methods:{
 changeHandler: function(){
  this.$emit('info', {title, image,description})
 }
}

在您的孩子部分中执行上述操作,在您的父母中执行以下操作

<news @info="info"></news>
<news-detail info="info"></news-detail>

您尚未提供组件的结构和层次结构,因此我不知道这是否对您有用。

其次,通过vuex

您可以commit()的值,并通过getters[]

进行访问

第三,通过事件总线,类似于第一个,但具有中央控制。