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
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.
The diffrence between the
style
and the:style
attribute is, thatstyle
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 variablecolor
to the attribute, not the word "color". The functionfunction toggleColor()
does exactly that, it toggles the value of the variablecolor
. 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.