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' 都无法获取到属性,想问下大家有什么好的解决方案?
回答:
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>
以上是 vue3非 setup 语法糖如何在 css v-bind 中使用当前组件的 props? 的全部内容, 来源链接: utcz.com/p/934878.html