Reputation: 33877
Let's say I have a div like below and my goal is to set it's css class to some computed string of classes based on the name of a vue data model property passed to the getClassText
method:
<div :class="getClassText('lastName')">
With this javascript:
new Vue({
el: '#app',
data: {
firstName: '',
lastName: ''
},
methods: {
getClassText: function (fieldName) {
var valueOfField = NeedHelpHere(fieldName);
//some complex calculations based on the valueOfFild
return resultOfComplexCalculations;
}
}
});
Inside the NeedHelpHere(fieldName)
method I need to be able to return value of a Vue data model property based property name. How can that be done with Vue?
Note: I realize I could call the method without the quoting the lastName and that would cause the property's value to be passed in.
<div :class="getClassText(lastName)">
But for the sake of understanding Vue better, I'd like to know how to call the method passing the property name as a string like this
<div :class="getClassText('lastName')">
With such an approach, inside the NeedHelpHere(fieldName)
method I need to be able to return value of a Vue data model property based property name. How can that be done with Vue?
Upvotes: 4
Views: 6820
Reputation: 9201
If you don't want pass value directly you can do it like this:
HTML:
<div id="app">
<div :class="getClassText('lastName')">fooo</div>
</div>
JS Part:
new Vue({
el: '#app',
data: {
firstName: '',
lastName: 'my-class'
},
methods: {
getClassText: function (fieldName) {
if (this.$data.hasOwnProperty(fieldName)) {
return this.$data[fieldName]
}
return
}
}
});
Demo: http://jsbin.com/rutavewini/edit?html,js,output
Upvotes: 8