I am trying to understand how Vue.js' directives work and how they can be used to manipulate the DOM. I have been experimenting with a simple example that should bind the "color" attribute of a div to a data property, but it is not working as expected.
Here is my code:
Copy code<div id="app">
<div v-bind:color="color"></div>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
color: 'red'
}
})
</script>
I have also tried using the v-bind
shorthand :color
and the v-bind
attribute with different variations of the property name such as :color
, :color.sync
, :color.once
, but it does not seem to work.
I have also looked into the documentation of Vue.js and read about directives, but I can't seem to find a way to get this to work. Can someone please explain to me how I can bind the color attribute of the div to the "color" data property in Vue.js?
What is the correct way to bind color attribute of div element with color data property in Vue.js and also please explain how it works internally?
CodePudding user response:
I think you want to set text color (CSS color attribute), right?
<div :style="{color: color}"></div>
The colon at the beginning of :style
makes it an attribute handled as vue expression. :style
is a special attribute in that it takes an object where keys are css properties in camel case (i.e. borderRadius
) and values are expressions, like the value of your color
variable. Have a look at class and style bindings in vue
CodePudding user response:
The data needs to return an object, like this:
data: function () {
return {
count: 0
}
}