如何在vue js中从父级修改子组件的颜色属性

问题描述

我有一个Card 组件:

<template>
  <v-card
    class="mx-auto"
    max-width="500"
    color=color
    outlined
    dark
  >
    <v-list-item three-line>
      <v-list-item-content>
        <div class="overline mb-4">
          OVERLINE
          {{color}}
        </div>
        <v-list-item-title class="headline mb-1">
          Headline 5
        </v-list-item-title>
        <v-list-item-subtitle>Greyhound divisely hello coldly fonwderfully</v-list-item-subtitle>
      </v-list-item-content>

      <v-list-item-avatar
        tile
        size="80"
        color="grey"
      ></v-list-item-avatar>
    </v-list-item>

    <v-card-actions>
      <v-btn
        outlined
        rounded
        text
      >
        Button
      </v-btn>
    </v-card-actions>
  </v-card>
</template>

<script>
  export default {
    name: 'Card',props: {
      color: String
    }
  }
</script>

从父组件我想将 color 传递给子组件。父组件的部分代码如下所示。

<template>
  <Card v-bind:color="color"/>
</template>

<script>
  export default {
   data() {
      return {
        color: "#FFC400"
      }
    },}
</script>

如您所见,我尝试使用道具将 color 从父级传递给子级,但是即使我能够将数据传递给子级,{{color}} 也会打印出#FFC400 我不确定如何将颜色值分配给 v-card 的颜色属性。我怎样才能做到这一点?谢谢。

解决方法

唯一缺少的是将 prop 绑定到 color<v-card> 属性,否则它只会接收字符串“color”,而不是该名称的变量。

您可以使用 v-bind:color="color" 或简写 :color="color"

<v-card
  class="mx-auto"
  max-width="500"
  :color="color"
  outlined
  dark
>