Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How vue calls methods from outside the component

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Editor to share with you how vue calls methods from outside the component, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

Call a method from outside the component

You can call the method ref from outside the component by giving it:

/ / somewhere in Parent.vue this.$refs.child.method ()

Typically, we use props and events to communicate between components. The prop is sent to the child component and the event is sent back to the parent component.

But sometimes you may encounter situations where you need the parent component to trigger a method in the child component. This is the only place where passing props down doesn't work.

You can pass a Boolean value down and have the subcomponent monitor it:

/ / Child.vueexport default {props: ['trigger'], watch: {shouldCallMethod (newVal) {if (newVal) {/ / call the method this.method ();} when the trigger is set to `true`

This works fine, but only for the first call. If you need to trigger this operation multiple times, you must clean up and reset the state. Then the logic looks like this:

The Parent component passes true to triggerprop

The Watch is triggered and the Child component invokes the method

The Child component issues an event telling the Parent component that the method has been triggered successfully

The Parent component resets trigger back to false, so we can do this again

Conversely, if we set ref on a subcomponent, we can call this method directly:

/ / somewhere in Parent.vue this.$refs.child.method ()

We broke the "props down, events up" rule and broke the package, but it's clearer and easier to understand. It's worth it!

This is all of the article "how vue invokes methods from outside the component". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report