1. provide/inject
provide/inject
It is an advanced technology used to pass data across components. It can inject data into a component and then allow all its descendants to access this data. Normally, we use it in the parent componentprovide
to provide data and then use it in the descendants componentinject
Come inject this data.
useprovide/inject
The advantage is that it allows us to pass data between the parent component and the child component without having to do cumbersome manuallyprops
transfer. It can make the code more concise and easy to maintain. But it should be noted thatprovide/inject
The data is non-responsive because provide/inject is a more underlying API that passes data based on dependency injection, rather than through a responsive system to achieve data update and synchronization.
Specifically, the data provided by the provide method will be injected into the inject property in the child component, but this data will not automatically trigger the re-render of the child component. If the data provided by the provide changes, the child component will not automatically sense these changes and update.
If you need to use the data provided by provide/inject in the child component and you want this data to be updated responsively, consider using Vue's responsive data instead of provide/inject. For example, data can be defined in the parent component and passed it to the child component through props, and the child component then sends data update events to the parent component through $emit, thereby achieving responsive data updates.
Here is a simple example showing how to provide data in the parent component and inject this data into the child component:
<!-- Parent component --> <template> <div> <ChildComponent /> </div> </template> <script> import ChildComponent from './'; export default { provide: { message: 'Hello from ParentComponent', }, components: { ChildComponent, }, }; </script> //The above provide can also be written in function formexport default { provide(){ return { message: } } }
<!-- Subcomponents --> <template> <div> <GrandchildComponent /> </div> </template> <script> import GrandchildComponent from './'; export default { inject: ['message'], components: { GrandchildComponent, }, }; </script>
<!-- Grandson Component --> <template> <div> <p>{{ message }}</p> </div> </template> <script> export default { inject: ['message'], }; </script>
In the example above, a parent component is provided with a name calledmessage
Data can be used in the descendants componentsinject
To inject this data and use it in the template. Note that theinject
An array is used in the options, which contains the attribute names that need to be injected. In this example, we only inject onemessage
attribute, so there is only one element in the array.
2. Custom v-model
To make custom Vue components support v-model, you need to implement a name calledvalue
and a prop namedinput
events. Inside the component,value
prop is bound to the internal state of the component and then triggers when modifying the internal stateinput
event.
Here is a simple example showing how to create a custom input box component and support v-model:
<template> <input :value="value" @input="$emit('input', $)" /> </template> <script> export default { name: 'MyInput', props: { value: String } }; </script>
In the above component, we define avalue
prop, this is the data bound to v-model. We will also have built-ininput
Forwarding events to a custominput
Events and update internal state in event handler. Now we can use v-model in the parent component to bind the value of this custom component, just like using a normal input box:
<template> <div> <my-input v-model="message" /> <p>{{ message }}</p> </div> </template> <script> import MyInput from './'; export default { components: { MyInput }, data() { return { message: '' }; } }; </script>
In the above code, we usev-model
Instructions for two-way bindingmessage
Data andMyInput
The value of the component. When the user enters text in the input box,MyInput
Components will triggerinput
Events and send their updated values to the parent component, achieving the effect of two-way binding.
3. Event Bus (EventBus)
The Vue event bus is an event handling mechanism that allows components to communicate to share information in applications. In an application, the event bus is usually a global instance that can be used to send and receive events.
Here are the steps to use the Vue event bus:
3.1 Create a global Vue instance as event bus:
import Vue from 'vue'; export const eventBus = new Vue();
3.2 In the component that needs to send events, use$emit
Method triggers events and passes data:
eventBus.$emit('eventName', data);
3.3 In components that need to receive events, use$on
Methods listen for events and process data:
eventBus.$on('eventName', (data) => { // Process data});
It should be noted that the event bus is global, so in different components, the uniqueness of the event name needs to be ensured.
In addition, it needs to be used before the component is destroyed$off
Method cancel event listening:
eventBus.$off('eventName');
This allows you to use event buses in your application to enable communication between components.
4. render method
Vue'srender
The method is used to render components' functions. It can be used instead of template syntax to generate DOM structures through code. Compared with template syntax,render
Methods have better type checking and code prompts.
The following details of Vue'srender
How to use the method:
4.1 Basic syntax
render
The basic syntax of the method is as follows:
render: function (createElement) { // Return a VNode}
increateElement
Is a function that creates a VNode (virtual node) and returns a VNode object.
4.2 Create VNode
To create a VNode, you can call itcreateElement
Function, this function accepts three parameters:
- Tag name or component name
- Optional attribute object
- Children node array
For example, the following code creates a text node that contains a text nodediv
element:
render: function (createElement) { return createElement('div', 'Hello, world!') }
If you want to create an element with a child, you can pass the child node as a third parameter tocreateElement
function. For example, the following code creates a two child elementsdiv
element:
render: function (createElement) { return createElement('div', [ createElement('h1', 'Hello'), createElement('p', 'World') ]) }
If you want to add attributes to an element, you can pass the attribute object as a second parameter tocreateElement
function. For example, the following code creates a style and event handlerbutton
element:
render: function (createElement) { return createElement('button', { style: { backgroundColor: 'red' }, on: { click: } }, 'Click me') }, methods: { handleClick: function () { ('Button clicked') } }
4.3 Dynamic data
render
Methods can generate content dynamically based on the state of the component. To berender
The data of the component is used in the method, which can be usedthis
Keywords to access the properties of the component instance. For example, the following code dynamically generates a counter based on the state of the componentdiv
element:
render: function (createElement) { return createElement('div', [ createElement('p', 'Count: ' + ), createElement('button', { on: { click: } }, 'Increment') ]) }, data: function () { return { count: 0 } }, methods: { increment: function () { ++ } }
4.4 JSX
Using Vuerender
When using methods, you can also use JSX (JavaScript XML) syntax, which makes it easier to write templates. To use JSX, you need to import it in the componentVue
andcreateElement
function, and inrender
Use JSX syntax in the method. For example, the following code uses JSX syntax to create a counter component:
import Vue from 'vue' export default { render() { return ( <div> <p>Count:{}</p> <button onClick={}>Increment</button> </div> ) }, data() { return { count: 0 } }, methods: { increment() { ++ } } }
Note that when using JSX, you need to use it{}
Wrap JavaScript expressions.
4.5 Generate functional components
In addition to generating ordinary components,render
Methods can also generate functional components. Functional components have no state, only receiveprops
As input, and return a VNode. Because functional components have no state, they have higher performance than normal components.
To generate a functional component, you can use the component definition to define thefunctional
The property is set totrue
. For example, the following code defines a functional component to display list items:
export default { functional: true, props: ['item'], render: function (createElement, context) { return createElement('li', ); } }
Note that in functional components,props
Passed as a second parameterrender
method.
Summarize
This is the end of this article about the four commonly used advanced methods in VUE. For more related contents of commonly used advanced methods in VUE, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!