SoFunction
Updated on 2025-04-12

UniApp uses setup syntax sugar to create and use custom components under Vue3

UniApp creates and uses custom components using setup syntax sugar under Vue3

In modern front-end development, Vue 3's<script setup>Syntax sugar greatly simplifies the writing and use of components. This article will explain in detail how to use Vue 3 in UniApp<script setup>Syntax creates custom components and uses them in other components.

1. Create custom components

First, we create a simple custom component. This component will receive some properties and show some basic content.

&lt;template&gt;
  &lt;view :style="styleObject"&gt;
    &lt;p v-if="showText"&gt;{{ text }}&lt;/p&gt;
    &lt;p&gt;Number: {{ number }}&lt;/p&gt;
    &lt;p&gt;Boolean: {{ boolean }}&lt;/p&gt;
    &lt;ul&gt;
      &lt;li v-for="item in array" :key="item"&gt;{{ item }}&lt;/li&gt;
    &lt;/ul&gt;
    &lt;p&gt;Object: {{  }} - {{  }}&lt;/p&gt;
    &lt;button @click="emitEvent"&gt;Click to trigger event&lt;/button&gt;
  &lt;/view&gt;
&lt;/template&gt;
&lt;script setup&gt;
import { defineProps, defineEmits, computed } from 'vue';
// Define the received propsconst props = defineProps({
  text: {
    type: String,
    default: 'Default text'
  },
  number: {
    type: Number,
    default: 0
  },
  boolean: {
    type: Boolean,
    default: false
  },
  array: {
    type: Array,
    default: () =&gt; []
  },
  object: {
    type: Object,
    default: () =&gt; ({ name: 'Default Name', age: 20 })
  }
});
// Define the triggered eventconst emit = defineEmits(['customEvent']);
// Compute properties, used to process style objectsconst styleObject = computed(() =&gt; ({
  marginTop:  + 'px',
  color:  ? 'red' : 'black'
}));
// Method: Trigger custom eventconst emitEvent = () =&gt; {
  emit('customEvent', 'This is a custom event');
};
&lt;/script&gt;
&lt;style scoped&gt;
/* Local styles within the component */
button {
  margin-top: 10px;
}
&lt;/style&gt;

Detailed explanation

1.1 Defining attributes (defineProps)

existWe usedefinePropsto define the properties that a component can receive. Each attribute has a type and default value:

const props = defineProps({
  text: {
    type: String,
    default: 'Default text'
  },
  number: {
    type: Number,
    default: 0
  },
  boolean: {
    type: Boolean,
    default: false
  },
  array: {
    type: Array,
    default: () =&gt; []
  },
  object: {
    type: Object,
    default: () =&gt; ({ name: 'Default Name', age: 20 })
  }
});

1.2 Defining Events (defineEmits)

We usedefineEmitsto define events that components can trigger. In this example, we define a name calledcustomEventEvents:

const emit = defineEmits(['customEvent']);

1.3 Calculate properties (computed)

We usecomputedTo create a computed propertystyleObject, it is passed according tonumberandbooleanProperties generate style objects:

const styleObject = computed(() => ({
  marginTop:  + 'px',
  color:  ? 'red' : 'black'
}));

1.4 Method (emitEvent)

We defined a methodemitEvent, when the user clicks the button, triggerscustomEventEvent, and pass a message:

const emitEvent = () =&gt; {
  emit('customEvent', 'This is a custom event');
};

2. Use custom components

Next, we're in another.vueImport and use this custom component in the file, passing properties and listening events at the same time.

&lt;template&gt;
  &lt;view&gt;
    &lt;MyComponent 
      text="Hello World!"
      :number="50"
      :boolean="true"
      :array="['Apple', 'banana', 'orange']"
      :object="{ name: 'Zhang San', age: 30 }"
      @customEvent="handleCustomEvent"
    /&gt;
  &lt;/view&gt;
&lt;/template&gt;
&lt;script setup&gt;
import MyComponent from './components/';
// Define a method to handle custom eventsconst handleCustomEvent = (message) =&gt; {
  ('Custom event trigger:', message);
};
&lt;/script&gt;
&lt;style&gt;
/* Page-level style */
&lt;/style&gt;

Detailed explanation

2.1 Importing and using custom components

existWe importMyComponentAnd use it in the template while passing properties and listening for events:

&lt;MyComponent 
  text="Hello World!"
  :number="50"
  :boolean="true"
  :array="['Apple', 'banana', 'orange']"
  :object="{ name: 'Zhang San', age: 30 }"
  @customEvent="handleCustomEvent"
/&gt;

2.2 Handling custom events

We defined a methodhandleCustomEventTo handle custom eventscustomEvent

const handleCustomEvent = (message) =&gt; {
  ('Custom event trigger:', message);
};

Summarize

Through the above steps, we created a custom componentMyComponent, and inUse it in. We pass multiple types of properties and listen for custom events. This method greatly enhances the reusability and maintainability of components.

This is the article about creating and using custom components of UniApp using setup syntax sugar under Vue3. For more information about UniApp Vue3 setup syntax sugar, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!