css - 在vue.js组件中,如何在css中使用props?

标签 css vue.js vuejs2 vue-component

我是 vue.js 新手。这是我的问题:

在这样的 *.vue 文件中:

<template>
  <div id="a">
  </div>
</template>

<script>
  export default {
    name: 'SquareButton',
    props: ['color']
  }
</script>

<style scoped>
    #a {
      background-color: ?
    }
<style>

我如何在 background-color: 中使用 Prop color(现在 在哪里?)。

谢谢。

最佳答案

你真的可以!

您应该在计算属性中定义 CSS 变量,然后将计算属性作为样式属性调用到需要 CSS 变量的元素,最后您可以在文档底部的标签中使用该变量。

new Vue({
  el: '#app',
  data: function() {
    return {
      baseFontSize: 1,
      bgHoverColor: "#00cc00",
      hoverContent: "Hovering!"
    }
  },
  computed: {
    cssProps() {
      return {
        '--hover-font-size': (this.baseFontSize * 2) + "em",
        '--bg-hover-color': this.bgHoverColor,
        '--hover-content': JSON.stringify(this.hoverContent)
      }
    }
  }
})
div {
  margin: 1em;
}

div.test:hover {
  background-color: var(--bg-hover-color);
  font-size: var(--hover-font-size);
}

div.test:hover::after {
  margin-left: 1em;
  content: var(--hover-content);
}
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app" :style="cssProps">

  <div>Hover text: <input type="text" v-model="hoverContent"></div>
  <div>Hover color: <input type="color" v-model="bgHoverColor"></div>

  <div class="test">Hover over me</div>
</div>

或在这里查看:https://codepen.io/richardtallent/pen/yvpERW/
在这里:https://github.com/vuejs/vue/issues/7346

关于css - 在vue.js组件中,如何在css中使用props?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42872002/

相关文章:

javascript - 从选定的下拉列表中获取值 Vue Js

Jquery 滑动切换

html - 使文本保留在一个 div 中

html - wordpress 网站页面加载不正确

HTML 电子邮件格式在 Outlook 中不起作用

javascript - vue.js 计算属性未触发

typescript - Nuxt/ typescript : Cannot access this - TS2339: Property 'XXX' does not exist on type

javascript - 模板中带有脚本标签的广告 [Vue.js]

javascript - 在Vue.js中的双大括号{{}}中渲染元素

html - Vue-Nuxt : Why can't I see the generated HTMLs correctly?