10

I have a plugin that sets some variables to vue's object prototype.

I need to access these variables from a prop's default property. How can I achieve this?

Using the following example, webpack throws some undefined error.

//...
props: {
    size: {
        type: String,
        required: false,
        default: this.$myPlugin.size
    }
}
1
  • Can you provide install frunction of your plugin? Commented Jul 23, 2019 at 20:30

1 Answer 1

13

For Vue 2, you can specify the default as a function that returns the default value. That should have access to the current instance as this.

props: {
    size: {
        type: String,
        required: false,
        default () {
            return this.$myPlugin.size
        } 
    }
}

The relevant line in the Vue source code is here if you're curious. Note that the function is explicitly called with vm as its this value.

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

3 Comments

Thanks. This works. Complete answer. They call it with the vm scope.
Is this only working on plugin? I have tried on a child component props, it seems the vm(this) is not available and return undefined instead. -> Found the reason, because my props is also a function, vm is not available for props with type Function.
For reference, for event functions as props, may put this in parameter so that the context become instance proxy for using _self to access vue instance. eg. this._self

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.