Search code examples
cssvue.jsvuejs2vue-component

In vue.js component, how to use props in css?


I'm new to vue.js. Here is my problem:

In a *.vue file like this:

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

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

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

How can I use the props color in background-color: (where is a ? now).

Thanks.


Solution

  • You don't. You use a computed property and there you use the prop to return the style of the div, like this:

    <template>
      <div id="a" :style="style" @mouseover="mouseOver()">
      </div>
    </template>
    
    <script>
      export default {
        name: 'SquareButton',
        props: ['color'],
        computed: {
          style () {
            return 'background-color: ' + this.hovering ? this.color: 'red';
          }
        },
        data () {
          return {
            hovering: false
          }
        },
        methods: {
          mouseOver () {
           this.hovering = !this.hovering
          }
        }
      }
    </script>
    
    <style scoped>
    <style>