【问题标题】:Pass data in vue from single parent component to child components将 vue 中的数据从单个父组件传递到子组件
【发布时间】:2019-07-12 13:55:19
【问题描述】:

我有一个 vue 组件,它是 page.vue。 我有一个子 vue 组件,它是 card.vue,如下所示。

我无法将数据注入到卡(子)组件中。

我尝试在内部注入数据并 在页面组件的数据函数中。

页面.vue

<template>
  <div class="container">
    <card></card>
  </div>
</template>

<script>
import Card from "../Card.vue"
export default {
    name: 'skills',
    components: {
      "card": Card
    },
    data: function() {
        return {
            message: "Skills"
        }
    }
}
</script>

Card.vue

<template>
  <div class="container drop-shadow">
  </div>
</template>

<script>
export default {
    name: 'card',
    data: function() {
        return {
            data: "",
        }
    }
}
</script>

我希望该卡可以从 Page.vue 以外的其他组件中重复使用。 需要根据显示的位置将数据注入卡片中。

【问题讨论】:

    标签: javascript vue.js vuejs2


    【解决方案1】:

    有两种方法可以向下传递数据。

    第一种是通过使用props

    方法一:

    <template>
      <div class="container">
        <card :message="message"></card>
      </div>
    </template>
    
    <script>
    import Card from "../Card.vue"
    export default {
        name: 'skills',
        components: {
          "card": Card
        },
        data: function() {
            return {
                message: "Skills"
            }
        }
    }
    </script>
    

    这将使数据在 Card.vue 中可用

    <template>
      <div class="container drop-shadow">{{ message }}
      </div>
    </template>
    
    <script>
    export default {
        name: 'card',
        props: ['message'],
        data: function() {
            return {
                data: "",
            }
        }
    }
    </script>
    

    方法 2: 您还可以在 Card.vue 中放置一个slot,这将允许您将内容放在父元素标签之间,就像这样。 页面.vue

    <template>
      <div class="container">
        <card>{{ message }}</card>
      </div>
    </template>
    
    <script>
    import Card from "../Card.vue"
    export default {
        name: 'skills',
        components: {
          "card": Card
        },
        data: function() {
            return {
                message: "Skills"
            }
        }
    }
    </script>
    

    Card.vue

    <template>
      <div class="container drop-shadow">
        <slot />
      </div>
    </template>
    
    <script>
    export default {
        name: 'card',
        data: function() {
            return {
                data: "",
            }
        }
    }
    </script>
    
    

    【讨论】:

    • 谢谢。我让它工作。但我无法让它与对象的传递一起工作。我错过了什么?
    • 你必须更具体
    • 我不确定传递对象是什么意思。你的意思是实际的javascript Object?你为什么要传递一个对象?
    猜你喜欢
    • 2020-09-25
    • 2017-10-20
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 2020-07-26
    • 2021-08-27
    • 1970-01-01
    相关资源
    最近更新 更多