Search code examples
javascriptvue.jsvuejs2quasar-frameworkquasar

How to add custom property in Quasar?


I want to add custom properties in Quasar framework, but when I set it the ESlint shows me this error: Array prototype is read only, properties should not be added

I want to add a extend method for Array:

Array.prototype.extend = function (other_array) {
    /* You should include a test to check whether other_array really is an array */
    other_array.forEach(function(v) {this.push(v)}, this)
}

Solution

  • When you extend an object, you change its behaviour.

    Changing the behaviour of an object that will only be used by your own code is fine. But when you change the behaviour of something that is also used by other code there is a risk you will break that other code.

    Your options here can be to create a function and import it:

    helpers.js

    let extend = function(other_array) {
      return other_array.forEach(function(v) {this.push(v)}, this)
    }
    
    export default extend;
    

    componentA.vue

    import extend from './helpers.js';
    
    // use extend as a normal function
    

    or we could be a little bit smarter and use native methods that Javascript already has:

    // will 'glue' two arrays together
    firstArray.concat(secondArray);
    
    // or using new ECMA syntax (spread operator)
    finalArray = [...firstArray, ...secondArray];