阿里云主机折上折
  • 微信号
Current Site:Index > Built-in components (view, scroll-view, swiper, etc.)

Built-in components (view, scroll-view, swiper, etc.)

Author:Chuan Chen 阅读数:56036人阅读 分类: uni-app

uni-app provides a series of built-in components that can meet most development needs, with strong cross-platform compatibility. Developers do not need to worry about underlying differences. Built-in components include basic containers, scrollable containers, slider views, etc., which play important roles in different scenarios.

view Component

The view component is the most basic container component in uni-app, similar to the div tag in HTML. It supports flex layout and can nest other components or content. The view component is commonly used to build page structures and supports style binding and event handling.

<template>
  <view class="container">
    <view class="box" @click="handleClick">Click me</view>
  </view>
</template>

<script>
export default {
  methods: {
    handleClick() {
      uni.showToast({
        title: 'Click event triggered'
      })
    }
  }
}
</script>

<style>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
.box {
  width: 200rpx;
  height: 200rpx;
  background-color: #007AFF;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>

The view component supports the hover-class property, which can add a style class when touched:

<view hover-class="hover-style" class="normal-style">
  Touch me to change color
</view>

<style>
.normal-style {
  background-color: #f0f0f0;
}
.hover-style {
  background-color: #e0e0e0;
}
</style>

scroll-view Component

The scroll-view component is a scrollable view area component used to handle content that exceeds the container size. It supports horizontal and vertical scrolling and can listen to scroll events.

Basic vertical scrolling example:

<scroll-view scroll-y style="height: 300px;">
  <view style="height: 800px; background-color: #f0f0f0;">
    Very long content
  </view>
</scroll-view>

Horizontal scrolling example:

<scroll-view scroll-x style="white-space: nowrap; width: 100%;">
  <view style="display: inline-block; width: 200px; height: 100px; background-color: red; margin-right: 10px;"></view>
  <view style="display: inline-block; width: 200px; height: 100px; background-color: green; margin-right: 10px;"></view>
  <view style="display: inline-block; width: 200px; height: 100px; background-color: blue;"></view>
</scroll-view>

The scroll-view also supports scrolling to a specified position:

<scroll-view scroll-y :scroll-top="scrollTop" style="height: 300px;">
  <view v-for="item in 50" :key="item" style="height: 50px; line-height: 50px;">
    Item {{item}}
  </view>
</scroll-view>
<button @click="scrollToTop">Scroll to top</button>

<script>
export default {
  data() {
    return {
      scrollTop: 0
    }
  },
  methods: {
    scrollToTop() {
      this.scrollTop = 0
    }
  }
}
</script>

swiper Component

The swiper component is a slider view container, commonly used to implement carousel effects. It supports autoplay, loop sliding, indicators, and other features.

Basic carousel example:

<swiper :autoplay="true" :interval="3000" :duration="500" indicator-dots>
  <swiper-item>
    <view class="swiper-item" style="background-color: red;">Page 1</view>
  </swiper-item>
  <swiper-item>
    <view class="swiper-item" style="background-color: green;">Page 2</view>
  </swiper-item>
  <swiper-item>
    <view class="swiper-item" style="background-color: blue;">Page 3</view>
  </swiper-item>
</swiper>

<style>
.swiper-item {
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
}
</style>

The swiper component also supports vertical sliding:

<swiper :vertical="true" style="height: 300px;">
  <swiper-item>
    <view class="swiper-item" style="background-color: #f0f0f0;">Top</view>
  </swiper-item>
  <swiper-item>
    <view class="swiper-item" style="background-color: #e0e0e0;">Middle</view>
  </swiper-item>
  <swiper-item>
    <view class="swiper-item" style="background-color: #d0d0d0;">Bottom</view>
  </swiper-item>
</swiper>

text Component

The text component is a text component used to display text content. Unlike directly using view to display text, the text component supports long-press selection, copying, and other functions.

<text selectable>This text can be selected by long-pressing</text>
<text space="ensp">This text has spaces</text>
<text decode>&nbsp;&lt;&gt;&amp;&apos;&ensp;&emsp;</text>

The text component also supports nesting and style inheritance:

<text style="font-size: 16px; color: #333;">
  Parent text
  <text style="color: red;">Child text</text>
</text>

image Component

The image component is an image component that supports multiple image formats and loading modes. It is more feature-rich than the HTML img tag.

<image src="/static/logo.png" mode="aspectFit" lazy-load></image>

The image component supports multiple mode property values:

  • scaleToFill: Scales the image without maintaining the aspect ratio
  • aspectFit: Scales the image while maintaining the aspect ratio
  • aspectFill: Scales the image while maintaining the aspect ratio
  • widthFix: Keeps the width unchanged while the height adjusts automatically
  • heightFix: Keeps the height unchanged while the width adjusts automatically

Example of handling loading failures:

<image :src="imageUrl" @error="handleImageError"></image>

<script>
export default {
  data() {
    return {
      imageUrl: 'https://example.com/image.jpg'
    }
  },
  methods: {
    handleImageError(e) {
      console.log('Image loading failed', e)
      this.imageUrl = '/static/default-image.jpg'
    }
  }
}
</script>

navigator Component

The navigator component is a page link component used to implement page navigation. It supports multiple navigation methods and parameter passing.

<navigator url="/pages/home/home" open-type="navigate">Go to Home</navigator>
<navigator url="/pages/about/about" open-type="redirect">Redirect to About</navigator>
<navigator url="/pages/detail/detail?id=123" open-type="navigate">Navigate with parameters</navigator>

Supported open-type values:

  • navigate: Keeps the current page and navigates to another page in the app
  • redirect: Closes the current page and navigates to another page in the app
  • switchTab: Navigates to a tabBar page
  • reLaunch: Closes all pages and opens a specific page in the app
  • navigateBack: Closes the current page and returns to the previous page or multiple levels
  • exit: Exits the mini-program

button Component

The button component is a button component that supports multiple styles and open capabilities.

<button type="primary">Primary Button</button>
<button type="default" plain>Default Button</button>
<button type="warn">Warning Button</button>
<button open-type="getUserInfo" @getuserinfo="getUserInfo">Get User Info</button>

The button component supports a loading state:

<button :loading="isLoading" @click="handleSubmit">Submit</button>

<script>
export default {
  data() {
    return {
      isLoading: false
    }
  },
  methods: {
    handleSubmit() {
      this.isLoading = true
      setTimeout(() => {
        this.isLoading = false
      }, 2000)
    }
  }
}
</script>

input Component

The input component is an input field component that supports multiple input types and functions.

<input v-model="username" placeholder="Enter username" />
<input type="number" v-model="age" placeholder="Enter age" />
<input password v-model="password" placeholder="Enter password" />
<input type="idcard" v-model="idCard" placeholder="Enter ID card number" />

The input component supports a confirm event:

<input v-model="searchText" @confirm="handleSearch" placeholder="Press Enter to search" />

<script>
export default {
  data() {
    return {
      searchText: ''
    }
  },
  methods: {
    handleSearch() {
      uni.showToast({
        title: `Search: ${this.searchText}`
      })
    }
  }
}
</script>

checkbox and radio Components

The checkbox component is a multi-select component, and the radio component is a single-select component.

<checkbox-group @change="checkboxChange">
  <label>
    <checkbox value="apple" checked />Apple
  </label>
  <label>
    <checkbox value="banana" />Banana
  </label>
</checkbox-group>

<radio-group @change="radioChange">
  <label>
    <radio value="male" checked />Male
  </label>
  <label>
    <radio value="female" />Female
  </label>
</radio-group>

<script>
export default {
  methods: {
    checkboxChange(e) {
      console.log('Selected values:', e.detail.value)
    },
    radioChange(e) {
      console.log('Selected value:', e.detail.value)
    }
  }
}
</script>

picker Component

The picker component is a scroll selector component that supports regular selectors, time selectors, date selectors, etc.

Regular selector example:

<picker :range="options" @change="handlePickerChange">
  <view>Current selection: {{options[selectedIndex]}}</view>
</picker>

<script>
export default {
  data() {
    return {
      options: ['Option 1', 'Option 2', 'Option 3'],
      selectedIndex: 0
    }
  },
  methods: {
    handlePickerChange(e) {
      this.selectedIndex = e.detail.value
    }
  }
}
</script>

Date selector example:

<picker mode="date" :value="date" start="2010-01-01" end="2030-12-31" @change="dateChange">
  <view>Select date: {{date}}</view>
</picker>

<script>
export default {
  data() {
    return {
      date: '2023-01-01'
    }
  },
  methods: {
    dateChange(e) {
      this.date = e.detail.value
    }
  }
}
</script>

switch Component

The switch component is a toggle switch component.

<switch :checked="isChecked" @change="switchChange" color="#ff0000" />
<view>Current state: {{isChecked ? 'On' : 'Off'}}</view>

<script>
export default {
  data() {
    return {
      isChecked: false
    }
  },
  methods: {
    switchChange(e) {
      this.isChecked = e.detail.value
    }
  }
}
</script>

slider Component

The slider component is a slider selector component.

<slider :value="sliderValue" min="0" max="100" @change="sliderChange" activeColor="#ff0000" />
<view>Current value: {{sliderValue}}</view>

<script>
export default {
  data() {
    return {
      sliderValue: 50
    }
  },
  methods: {
    sliderChange(e) {
      this.sliderValue = e.detail.value
    }
  }
}
</script>

textarea Component

The textarea component is a multi-line input field component.

<textarea v-model="content" placeholder="Enter content" auto-height maxlength="200" />
<view>Entered {{content.length}}/200 characters</view>

<script>
export default {
  data() {
    return {
      content: ''
    }
  }
}
</script>

progress Component

The progress component is a progress bar component.

<progress :percent="progressPercent" show-info stroke-width="5" />
<button @click="addProgress">Increase Progress</button>

<script>
export default {
  data() {
    return {
      progressPercent: 0
    }
  },
  methods: {
    addProgress() {
      if (this.progressPercent < 100) {
        this.progressPercent += 10
      }
    }
  }
}
</script>

Component Styles and Platform Differences

Built-in components in uni-app may have subtle style differences across platforms. To ensure a consistent appearance, conditional compilation or unified style overrides can be used.

<style>
/* Common styles */
.button {
  padding: 10px 15px;
}

/* Mini-program specific styles */
/* #ifdef MP-WEIXIN */
.button {
  border-radius: 4px;
}
/* #endif */

/* H5 specific styles */
/* #ifdef H5 */
.button {
  border-radius: 8px;
}
/* #endif */
</style>

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.