Home >Web Front-end >Front-end Q&A >How to pass parameters to irrelevant components in Vue
In Vue, components can usually pass data through props attributes, but sometimes we need to pass data between unrelated components.
For example, we may need to pass data from one component to another component, but the two components may not have any connection. In this case, we can use Vue's event system to implement communication between non-parent and child components. Specifically, we can use the $on and $emit methods in Vue to send and receive events.
$on method is used to register a custom event in the current component. When the event is triggered, the current component can perform the corresponding operation. The $emit method is used to trigger a custom event and pass the specified parameters to all components listening to the event.
The example is as follows:
<!-- 组件A --> <template> <div> <!-- 触发事件 --> <button @click="sendDataToB">传递数据给组件B</button> </div> </template> <script> export default { methods: { sendDataToB() { // 发送事件 this.$emit('sendData', '这是来自组件A的数据') } } } </script>
<!-- 组件B --> <template> <div> <!-- 监听事件并接收数据 --> <div>收到的数据:{{ receivedData }}</div> </div> </template> <script> export default { data() { return { receivedData: '' } }, mounted() { // 监听事件 this.$on('sendData', (data) => { this.receivedData = data }) } } </script>
In this example, we registered a custom event named "sendData" in component A and used the $emit method to trigger the event. The $emit method will pass the string "This is the data from component A" as a parameter to all components listening to the event.
In component B, we use the $on method in the mounted life cycle hook to listen to the event "sendData", and update the data receivedData of component B in the response function. At this point, component B can receive the data passed from component A.
It should be noted that communication between non-parent and child components needs to be implemented using a specialized event system, so as to avoid infinite nesting of dolls between components and making the code difficult to maintain. Therefore, in actual development, we should try to limit the communication between components to parent-child components.
The above is the detailed content of How to pass parameters to irrelevant components in Vue. For more information, please follow other related articles on the PHP Chinese website!