Passing style directive value to a component in Vuejs

131 Views Asked by At

I am trying to add padding to a shared button component through :style directive. For some reasons, the changes doesn't show up on the button. This shared component requires different padding based on different scenario so I cannot add it directly inside my button.vue

I'm new to Vuejs and would really appreciate if anyone can suggest the problem.

        <Button
          @on-click="currentStep = 2"
          :text= "Next"
          :style="padding: 12px 15px 12px 15px"
        />
1

There are 1 best solutions below

1
On

If you bind something in Vue, then the value that you pass is JavaScript code.

In your case padding: 12px 15px 12px 15px will be interpret as JavaScript and it is not a valid JavaScript line.

So if you want to pass a text, then use quotes around it, like

:style="'padding: 12px 15px 12px 15px'"

You can also pass an object instead

:style="{ padding: '12px 15px 12px 15px' }"

Playground

Vue.createApp({
  data() {
    return {
      myStyle: { color: 'green' }
    }
  }
}).mount('#app')
#app { line-height: 1.75; }
[v-cloak] { display: none; }
.comment { color: #A0A0A0}
<div id="app">
  <button :style="'color: red'">red</button><br/>
  <button :style="{ color: 'blue' }">blue</button><br/>
  <button :style="myStyle">green</button> 
  <span class="comment"> &#8592; over data property</span><br/>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>