Home  >  Article  >  Web Front-end  >  Can props pass functions in vue?

Can props pass functions in vue?

WBOY
WBOYOriginal
2022-06-16 10:39:067795browse

Props in vue can pass functions; strings, arrays, numbers and objects can be passed as props in vue. Props are mainly used to pass values ​​​​in components. The purpose is to receive data passed from the outside. The syntax is " export default {methods: {myFunction() {// ...}}};".

Can props pass functions in vue?

The operating environment of this tutorial: Windows 10 system, Vue3 version, Dell G3 computer.

Props transfer function in vue

A common question often asked by newbies in Vue. Strings, arrays, numbers, and objects can be passed as props. But can you pass a function as a props?

Although it is possible to pass a function as a props, this is not good. On the contrary, Vue has a feature designed specifically to solve this problem, let's take a look next.

Passing functions to components

It is relatively simple to get a function or method and pass it as a prop to a child component. In fact, it works exactly the same way as passing any other variable:

<template>
  <ChildComponent :function="myFunction" />
</template>

export default {
  methods: {
    myFunction() {
      // ...
    }
  }
};

As said before, you should never do anything like this in Vue.

Why? Vue has something better.

React vs Vue

If you have used React, you will be used to passing functions.

In React, we can pass a function from the parent component to the child component so that the child component can communicate upwards with the parent component. Props and data flow downward, function calls flow upward.

However, Vue has a different mechanism to implement child-to-parent communication, Vue uses events.

This is the same way the DOM works - Vue's way is more consistent with browsers than React. Elements can emit events and can listen to these events.

Therefore, although it is possible to pass functions as props in Vue, it is considered an anti-pattern.

Using Events

Events are how we communicate with parent components in Vue.

Here is a short example to illustrate how events work.

First, we will create the subcomponent that emits an event when created:

// ChildComponent
export default {
  created() {
    this.$emit(&#39;created&#39;);
  }
}

In the parent component, we listen for the event:

<template>
  <ChildComponent @created="handleCreate" />
</template>

export default {
  methods: {
    handleCreate() {
      console.log(&#39;Child has been created.&#39;);
    }
  }
};

Event There is so much more that can be done, and this is just scratching the surface. It is highly recommended to check out the official Vue documentation to learn more about it, it is definitely worth reading.

But events cannot completely solve all our problems.

Accessing data in the scope of the parent component from the child component

In many cases, the problem we are trying to solve is accessing data from different scopes.

The parent component has one scope, and the child component has another scope.

Usually, we want to access the value in the child component from the parent component, or access the value in the parent component from the child component. Vue prevents us from doing this directly, which is a good thing.

It makes our components more encapsulated and improves their reusability. This makes our code cleaner and avoids a lot of headaches in the long run.

But sometimes we may try to bypass this problem through functions.

「Get the value from the parent class」

If you want the child component to access the method of the parent component, then passing the method directly as a prop seems simple and clear.

In the parent component we will do this:

<!-- Parent -->
<template>
  <ChildComponent :method="parentMethod" />
</template>

// Parent
export default {
  methods: {
    parentMethod() {
      // ...
    }
  }
}

In our child component, use the passed in method:

// Child
export default {
  props: {
    method: { type: Function },
  },
  mounted() {
    // Use the parent function directly here
    this.method();
  }
}

What are the problems with doing this?

This is not entirely wrong, but using events would be better in this case.

Then, when needed, the child component does not call the function, but just emits an event. The parent component will then receive the event, call the function, and the assembly will update the prop passed to the child component.

This is a better way to achieve the same effect.

In other cases, we may want to get a value from a child element into the parent element, and we use a function for this.

For example, you might be doing this. The parent function accepts the value of the child function and processes it:

<!-- Parent -->
<template>
  <ChildComponent :method="parentMethod" />
</template>

// Parent
export default {
  methods: {
    parentMethod(valueFromChild) {
      // Do something with the value
      console.log(&#39;From the child:&#39;, valueFromChild);
    }
  }
}

Call the incoming method in the child component and pass the value of the child component as a parameter of the method:

// Child
export default {
  props: {
    method: { type: Function },
  },
  data() {
    return { value: &#39;I am the child.&#39; };
  },
  mounted() {
    // Pass a value to the parent through the function
    this.method(this.value);
  }
}

This It's not entirely wrong, it works.

It's just that this isn't the best way to do it in Vue. Instead, events are better suited to solving the problem. We can achieve the exact same thing using events

<!-- Parent -->
<template>
  <ChildComponent @send-message="handleSendMessage" />
</template>

// Parent
export default {
  methods: {
    handleSendMessage(event, value) {
      // Our event handler gets the event, as well as any
      // arguments the child passes to the event
      console.log(&#39;From the child:&#39;, value);
    }
  }
}

In child components we emit events:

// Child
export default {
  props: {
    method: { type: Function },
  },
  data() {
    return { value: &#39;I am the child.&#39; };
  },
  mounted() {
    // Instead of calling the method we emit an event
    this.$emit(&#39;send-message&#39;, this.value);
  }
}

Events are very useful in Vue, but they also don't 100% solve our problem question. Sometimes, we need to access the child's scope from the parent in a different way.

For this, we use scoped slots!

Using Scope Slots

Scope slots are a more advanced topic, but they are also very useful. In fact, I think they are one of the most powerful features Vue has to offer.

They weaken the boundary between child scope and parent scope. But it's done in a very clean way, making our components as composable as before.

If you want to know more about how scope slots work, you can read the official documentation first, or we will explain it next time.

[Related recommendations: "vue.js Tutorial"]

The above is the detailed content of Can props pass functions in vue?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn