css - 将 css 作为组件参数传递

标签 css vue.js

我想创建一个带有一些 CSS 参数的组件。我知道我不能做这样的事情

<template>
  <div id="textContainer">
    {{ content }}
  </div>
</template>

<script>
export default {
  props: {
    content: String,
    textAlign: String
  }
};
</script>

<style scoped>
#textContainer {
  text-align: {{textAlign}}; // this won't work
}
</style>

但我想创建一个组件来处理 HTML 代码中的 css 参数,就像这个例子

<template>
  <div id="textContainer" :style="'text-align: {{textAlign}}'">
    this should be right aligned
  </div>
</template>

<script>
export default {
  props: {
    textAlign: String
  }
};
</script>

<style scoped>
#textContainer {
  text-align: center;
}
</style>

并使用它

<MyComponent textAlign="right" />

我不知道这是行不通还是我的语法有误。我提供了一个工作示例

https://codesandbox.io/s/my002w6oqy

并想知道是否有一种方法可以创建具有动态 css 参数的组件。否则我将不得不创建仅 css 样式不同的组件。

最佳答案

You can use the object syntax :

<template>
  <div id="textContainer" :style="{ textAlign }">
    this should be right aligned
  </div>
</template>

<script>
export default {
  props: {
    textAlign: String
  }
};
</script>

https://codesandbox.io/s/wnpl6zvnlw

关于css - 将 css 作为组件参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53785970/

相关文章:

docker - 带有热重载的 docker 容器上的 Vue.js 应用程序

html - 电子邮件图表 - 条形图、面积图和饼图

javascript - 使用退格键或删除按钮时提交按钮颜色不改变

php - 在 php 中从 header 中包含 css

javascript - 2 个不同元素的外观相同

image - 在 vuejs 中的图像中包含路由器链接标签

vue.js - 在 vue-cli 3 项目中使用带有 npm-link 的 vuex store 丢失 $store

php - Laravel 将访问器传递给 vue

jquery - 获取 HTML5 中所需的 CSS 浏览器用途

javascript - vuejs中渲染完所有图片后执行代码