Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value of Vue data model property based property name?

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?

like image 226
RonC Avatar asked Feb 05 '23 15:02

RonC


1 Answers

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

like image 65
Belmin Bedak Avatar answered Feb 07 '23 12:02

Belmin Bedak