SoFunction
Updated on 2025-04-05

Summary of four commonly used advanced methods in VUE

1. provide/inject

provide/injectIt 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 componentprovideto provide data and then use it in the descendants componentinjectCome inject this data.

useprovide/injectThe advantage is that it allows us to pass data between the parent component and the child component without having to do cumbersome manuallypropstransfer. It can make the code more concise and easy to maintain. But it should be noted thatprovide/injectThe 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 calledmessageData can be used in the descendants componentsinjectTo inject this data and use it in the template. Note that theinjectAn array is used in the options, which contains the attribute names that need to be injected. In this example, we only inject onemessageattribute, 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 calledvalueand a prop namedinputevents. Inside the component,valueprop is bound to the internal state of the component and then triggers when modifying the internal stateinputevent.

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 avalueprop, this is the data bound to v-model. We will also have built-ininputForwarding events to a custominputEvents 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-modelInstructions for two-way bindingmessageData andMyInputThe value of the component. When the user enters text in the input box,MyInputComponents will triggerinputEvents 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$emitMethod triggers events and passes data:

eventBus.$emit('eventName', data);

3.3 In components that need to receive events, use$onMethods listen for events and process data:

eventBus.$on('eventName', (data) =&gt; {
  // 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$offMethod 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'srenderThe 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,renderMethods have better type checking and code prompts.

The following details of Vue'srenderHow to use the method:

4.1 Basic syntax

renderThe basic syntax of the method is as follows:

render: function (createElement) {
  // Return a VNode}

increateElementIs a function that creates a VNode (virtual node) and returns a VNode object.

4.2 Create VNode

To create a VNode, you can call itcreateElementFunction, 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 nodedivelement:

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 tocreateElementfunction. For example, the following code creates a two child elementsdivelement:

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 tocreateElementfunction. For example, the following code creates a style and event handlerbuttonelement:

render: function (createElement) {
  return createElement('button', {
    style: { backgroundColor: 'red' },
    on: {
      click: 
    }
  }, 'Click me')
},
methods: {
  handleClick: function () {
    ('Button clicked')
  }
}

4.3 Dynamic data

renderMethods can generate content dynamically based on the state of the component. To berenderThe data of the component is used in the method, which can be usedthisKeywords to access the properties of the component instance. For example, the following code dynamically generates a counter based on the state of the componentdivelement:

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 VuerenderWhen 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 componentVueandcreateElementfunction, and inrenderUse 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,renderMethods can also generate functional components. Functional components have no state, only receivepropsAs 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 thefunctionalThe 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,propsPassed as a second parameterrendermethod.

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!