SoFunction
Updated on 2025-04-05

uni-app custom component detailed code example

Preface

In uni-app, we can use Vue's component syntax to customize components, including component data, properties, events, methods, etc. Custom components allow us to easily reuse and modify components in different projects, while improving the scalability of component libraries and application flexibility.

In uni-app, we can store components in the project's component directory. uni-app only supports vue single-file components (.vue).

1. Register

1. Global registration

  uni-appSupports configuration of global components, and needs to beGlobal registration is performed, and after registration, you can use this component on all pages.

// Global import and registration are carried outimport Vue from 'vue'
import pageHead from './components/'
('page-head',pageHead)

// You can use components directly in<template>
	<view>
		<page-head></page-head>
	</view>
</template>

2. Local registration

There are two ways to introduce components on the page, and it is recommended to use them.easycomMethod introduction.

1. Traditional vue specifications

In the page, byimportIntroducing components incomponentsThe component you want to use is defined in the options.

	<!-- Introduced uni-badge Components-->
	<template>
		<view>
            <!-- 3.使用Components -->
			<uni-badge text="1"></uni-badge>
		</view>
	</template>
	<script>
        //1. Import components (This step belongs to the traditional vue specification, but this step can be omitted under easycom in uni-app)		import uniBadge from '@/components/uni-badge/';
		export default {
            //2. Register components (This step belongs to the traditional vue specification, but this step can be omitted under easycom in uni-app)			components:{uniBadge }
		}
	</script>

Way

Bringing component introduction into one step. As long as the components are installed in the projectcomponentsIn the directory and comply withcomponents/component name/component name.vueDirectory structure. You can use it directly on the page without quoting or registering.

	<!-- Introduced uni-badge Components-->
	<template>
		<view>
            <!-- 直接使用Components -->
			<uni-badge text="1"></uni-badge>
		</view>
	</template>
	<script>
		// There is no need to import here, nor does it require the uni-badge component to be registered in components.  You can use it directly in template		export default {
			data() {
				return {
				}
			}
		}
	</script>

2. Parent-child component communication

There are two ways of communication between the father and son components: father to son and son to father. Among them, the method of passing the child by the parent is implemented through props, and the child component receives the values ​​passed by the outside world to the component inside the component through props. The way for the child to pass the parent is to pass parameters through the $emit trigger event. The parent component listens to this event to receive the data passed by the child component.

Sample code for parent-passing child components:

The parent component passes message to the child component through the props property. The child component receives this value through props and displays it in the template.

<!-- Parent component -->
<template>
  <div>
    <child-component :message="parentMessage"></child-component>
  </div>
</template>

<script>
import ChildComponent from './';
export default {
  components: {
    ChildComponent,
  },
  data() {
    return {
      parentMessage: 'Hello from parent!',
    };
  },
};
</script>


<!-- Subcomponents -->
<template>
  <div>
    {{ message }}
  </div>
</template>

<script>
export default {
  props: ['message'],
};
</script>

Sample code for child pass parent component:

The child component triggers an event named childEvent through $emit and passes the data as a parameter to the parent component. The parent component listens to this event to receive the data passed by the child component and processes it in the handleChildEvent method.

<!-- Parent component -->
<template>
  <div>
    <child-component @childEvent="handleChildEvent"></child-component>
  </div>
</template>

<script>
import ChildComponent from './';
export default {
  components: {
    ChildComponent,
  },
  methods: {
    handleChildEvent(data) {
      ('Received data from child component:', data);
    },
  },
};
</script>

<!-- Subcomponents -->
<template>
  <div>
    <button @click="sendDataToParent">Send data to parent</button>
  </div>
</template>

<script>
export default {
  methods: {
    sendDataToParent() {
      const data = 'Hello from child!';
      this.$emit('childEvent', data);
    },
  },
};
</script>

3. uni.$on and uni.$emit

uni.$on is a global event listening method in uni-app, used to listen for triggers of specified events outside of pages or components. When the event is triggered, the passed callback function is executed. Using the uni.$on method can avoid the problem of manually registering and logging out the event listener in every page or component, improving code reusability and maintainability.

uni.$emit is a global event trigger that sends events to the parent component or global event trigger.

Sample code:

//Subcomponent triggers custom event<template>
  <div>
    <button @click="sendDataToParent">Send data to parent</button>
  </div>
</template>

<script>
export default {
  methods: {
    sendDataToParent() {
      const data = 'Hello from child!';
      uni.$emit('childEvent', data); // Trigger custom event    },
  },
};
</script>

// Listen to custom events triggered by child components in parent componentexport default {
  onLoad() {
    uni.$on('childEvent', ); // Register event listener  },
  beforeDestroy() {
    uni.$off('childEvent', ); // Log out the event listener  },
  methods: {
    handleChildEvent(data) {
      ('Received data from child component:', data);
    },
  },
};

4. Slot slot

Slots are a way to pass content to subcomponents. A slot is essentially an extension of a child component. The parent component passes content to a specified location inside the child component through a slot slot. The display of slots is not displayed and how to display is controlled by the parent component, while the display of slots is controlled by the child component.

Slot sample code:

<!-- Subcomponents -->
<template>
  <div>
    <slot name="header"></slot> <!-- Use named slots -->
    <slot></slot> <!-- Use default slot -->
    <slot name="footer"></slot> <!-- Use named slots -->
  </div>
</template>

<script>
export default {};
</script>

<!-- Parent component -->
<template>
  <div>
    <child-component>
      <template v-slot:header>
        <h2>The head of the component</h2>
      </template>
      <p>Contents of components。</p>
      <template v-slot:footer>
        <button @click="handleClick">Click me</button>
      </template>
    </child-component>
  </div>
</template>

<script>
import ChildComponent from './';
export default {
  components: {
    ChildComponent
  },
};
</script>

5. ref

Used to register reference information for elements or children, and the reference information will be registered in the parent component.$refson the object.

If used on a normal DOM element, the reference points to the DOM element; if used on a child component, the reference points to the component instance.On the non-H5 side, it can only be used to obtain custom component instances, but cannot be used to obtain built-in component instances (such as view, text).

<!-- NoH5The terminal does not support passingthis.$Come and get itviewExample -->
<view ref="content">hello</view>

<!-- Supportedthis.$Come and get itchild-componentExample -->
<child-component ref="child"></child-component>

Code example:

<!-- base-inputSubcomponent page -->
<template>
	<view>
		<input :focus="isFocus" type="text" placeholder="Please enter content" />
	</view>
</template>
<script>
	export default {
		name:"base-input",
		data() {
			return {
				"isFocus":false
			};
		},
		methods:{
			focus(){
				 = true
			}
		}
	}
</script>

<!-- index Parent component page -->
<template>
	<view>
		<base-input ref="usernameInput"></base-input>
		<button type="default" @click="getFocus">Get focus</button> 
	</view>
</template>
<script>
	export default {
		methods:{
			getFocus(){
				//Call the focus method through the ref defined by the component				this.$()
			}
		}
	}
</script>

Summarize

This is the end of this article about uni-app custom components. For more related uni-app custom components, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!