简体   繁体   中英

Vue.js call method in the data

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?

你需要使用this

title: this.capitalizeFirstLetter('title'),

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM