4

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?

0

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.