Klausette
Klausette

Reputation: 412

VueJS: How to to access parent function in child to conditionally render css classes?

I have a parent component with a function like (simplified example)

isValid(value) { return value > validationModifier }

Both the parent and the child use that function to conditionally render e.g. CSS classes. So in my child I would like to use:

:class="{'my-class' : isValid(myValue)}"

But I don't have access to this function. I want to avoid duplicating it in the child, and I don't see how emitting an event would work in this case. What is the appropriate way to deal with this?

Upvotes: 0

Views: 665

Answers (3)

rjcarl
rjcarl

Reputation: 742

@Joel H's answer is one of the ways to reuse functions in Vue. Another way is to use dependency injection in Vue. See https://v2.vuejs.org/v2/guide/components-edge-cases.html#Dependency-Injection

You just have to provide the method and all the children components of the ParentComponent can access that isValid method. Dependency injection in Vue is not limited to functions only, you can pass variables and data too.

export default {
  name: 'ParentComponent',
  ...
  methods: {
    isValid(value) { return value > validationModifier },
  },
  provide() {
    return {
      isValid: this.isValid
    }
  }
}

and in your ChildComponent ...

export default {
  name: 'ChildComponent',
  ...
  inject: ['isValid']
}

Now you can use the function in your ChildComponent using this.isValid(yourValueHere).

Upvotes: 0

Henri
Henri

Reputation: 801

You can pass the function to the child like a classical function prop https://v2.vuejs.org/v2/guide/components-props.html#Prop-Types No need to use the event/emit system here.

<child v-bind:is-valid="isValid"></child>

Upvotes: 0

Joel H
Joel H

Reputation: 61

If the function has reusable logic, rather than specific to that parent component, then I would use a mixin. If you want to add any other shared logic (methods, computed functions) you can edit the mixin and don't have to explicitly add the new parameter to parent and child

mixin code:

const myMixin = {
    methods:{
        isValid(param1){
            return param1 < validationModifier 
        }
    
    }
}

then to inject into any of your components

{
  name: "my-custom-component",
  mixins:[myMixin],
  methods:{}
}

Upvotes: 1

Related Questions