skip to Main Content

In the vue website, I found an example confusing.
In <script>, it says

const color = ref('green')
function toggleColor() {
  color.value = color.value === 'green' ? 'blue' : 'green'
}

In <template>,

<p :style="{ color }" @click="toggleColor">
    This should be green, and should toggle between green and blue on click.
</p>

I don’t quite understand how does :style="{ color }" work, can anyone help me please?

I have searched online about this problem and didn’t seem to find another example of this. I have also tried other ways like deleting the {} but it didn’t work.

2

Answers


  1. I think the complete writing should be :style="{color: color}".
    This should be inspired by the object notation in JavaScript, where the key and value in an object can be omitted if they are the same.

    <p :style="{ color: color }" @click="toggleColor">
      This should be green, and should toggle between green and blue on click.
    </p>
    
    Login or Signup to reply.
  2. The diffrence between the style and the :style attribute is, that style is static and :style is dynamic. that means the value of :style is not limited to plain text but you can do javascript operations in it, like you do in your example. You pass the content of the variable color to the attribute, not the word "color". The function function toggleColor() does exactly that, it toggles the value of the variable color. and with @click="toggleColor you call the function if you click on the element. So everytime you click on the element, the color of the element should change.Hope that helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search