vue3非 setup 语法糖如何在 css v-bind 中使用当前组件的 props?

如下为组件代码:

<template>
  <div class="download-btn" @click.stop="click">
    {{btnTxt}}
  </div>
</template>
<script>

export default {
  props: {
    width: {
      type: String,
      default: '250px',
      required: false
    },
    height: {
      type: String,
      default: '45px',
      required: false
    },
    color: {
      type: String,
      default: '#fff',
      required: false
    },
    bgColor: {
      type: String,
      default: '#3A8BFF',
      required: false
    },
    btnTxt: {
      type: String,
      required: false
    }
  },
  name: 'download-btn',
  setup(props, { emit }) {
    const click = (event) => {
      emit('ctaClick', event)
    }
    return {
      click
    }
  }
}
</script>
<style lang="less">
.download-btn {
  width: v-bind('props.width');
  height: v-bind(height);
  color: v-bind(color);
  background-color: v-bind('props.bgColor');
  font-size: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 15px;
  .showline(1);
}
</style>

当前组件传入的 props 属性,我想直接通过 css v-bind 使用,但是无论直接使用属性名称,还是 'props.xxx' 都无法获取到属性,想问下大家有什么好的解决方案?

阅读 3.8k
2 个回答

props 只会在 template 里自动展开,但 style 里并不会。style 里只能访问到你 setup 里 return 的那些成员。所以你要想访问 props,把它 return 就好了:

<script>
export default {
   /* 略 */
   setup(props) {
        return {
            props
        };
    }
}
</script>
<style lang="less">
.download-btn {
    width: v-bind('props.width');
    height: v-bind('props.height');
    color: v-bind('props.color');
    background-color: v-bind('props.bgColor');
    /* 略 */
}
</style>
<template>
  <div 
    class="download-btn" 
    @click.stop="click"
    :style="{
      width: width,
      height: height,
      color: color,
      backgroundColor: bgColor
    }"
  >
    {{btnTxt}}
  </div>
</template>

<script>
export default {
  props: {
    width: {
      type: String,
      default: '250px',
      required: false
    },
    height: {
      type: String,
      default: '45px',
      required: false
    },
    color: {
      type: String,
      default: '#fff',
      required: false
    },
    bgColor: {
      type: String,
      default: '#3A8BFF',
      required: false
    },
    btnTxt: {
      type: String,
      required: false
    }
  },
  name: 'download-btn',
  setup(props, { emit }) {
    const click = (event) => {
      emit('ctaClick', event)
    }
    return {
      click
    }
  }
}
</script>

<style lang="less">
.download-btn {
  font-size: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 15px;
  .showline(1);
}
</style>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题