
在Vue 3非setup语法糖组件中动态绑定props到style标签
本文介绍如何在不使用setup语法糖的Vue 3组件中,通过v-bind动态绑定从props接收的数据到style标签。 直接在标签内使用props.width等方式无效,因为Vue 3编译器处理和的方式不同。
问题:在标签内无法直接访问props。
解决方案:在setup函数中返回props对象,然后在中通过v-bind访问这些属性。
立即学习“前端免费学习笔记(深入)”;
修改后的script部分代码:
export default {
props: {
width: { type: String, default: '250px' },
height: { type: String, default: '45px' },
color: { type: String, default: '#fff' },
bgcolor: { type: String, default: '#3a8bff' },
btntxt: { type: String }
},
name: 'download-btn',
setup(props, { emit }) {
const click = (event) => { emit('ctaclick', event) };
return { props, click };
}
};
修改后的部分代码:
.download-btn {
width: :v-bind(props.width);
height: :v-bind(props.height);
color: :v-bind(props.color);
background-color: :v-bind(props.bgcolor);
font-size: 20px;
display: flex;
justify-content: center;
align-items: center;
border-radius: 15px;
/* .showline(1); // 此行代码含义不明确,建议移除或解释 */
}
注意:在中使用v-bind时,需要在属性值前加上冒号:。 通过此方法,即可在非setup语法糖的Vue 3组件中,动态绑定props到style标签。










