1

I am new to vue.js and I want to call a method in the data so something like this:

data() {
        return {
            title: capitalizeFirstLetter('title'),
        };
    },

and my vue mixin which I imported to my main.js

Vue.mixin({
  methods: {
    capitalizeFirstLetter(str) {
        return str.charAt(0).toUpperCase() + str.slice(1);
    }    
  }
})

but this doesnt work, I cant call capitalizeFirstLetter in the data. Is it possible to call a method in data?

2 Answers 2

2

Please ensure that you have registered the mixin in the component using mixin property in component.

After that you can access capitalizeFirstLetter method defined inside the mixin using this.capitalizeFirstLetter

Working fiddle

const myMixin = {
  methods: {
    capitalizeFirstLetter(str) {
      return str.charAt(0).toUpperCase() + str.slice(1);
    }
  }
}

new Vue({
  el: "#app",
  mixins: [myMixin],
  data() {
    return {
      title: this.capitalizeFirstLetter('title'),
    };
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  {{ title }}
</div>

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

Comments

1

You need to use this

title: this.capitalizeFirstLetter('title'),

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.