uni-app自定义组件的使用

以查看专辑详情为例:

步骤

  1. 在 src 根目录下新建 components目录,存放公共组件
<!-- src/components/goDetail.vue -->
<template>
  <view @click="handleClick">
    <slot></slot> <!-- 插槽占位 -->
  </view>
</template>
<script>
export default {
     
     
  props: {
     
      // vue中父子组件传值 子组件接收
    list: Array, // 查看的图片列表
    index: Number // 当前图片的下标
  },
  data () {
     
     
    return {
     
     }
  },
  methods: {
     
     
    handleClick () {
     
     
      // 1. 将数据缓存下来 保存到全局数据中
      getApp().globalData.imgList = this.list
      getApp().globalData.imgIndex = this.index
      // 2. 跳转 uni.navigateTo()
      uni.navigateTo({
     
     
        url: "/pages/imgDetail/index" // 此路径在pages.json中有定义
      })
    }
  }
}
</script>
  1. 自定义组件的使用
<!-- src/pages/album/index.vue -->
<template>
  	<!-- ... 省略部分代码-->
    <!-- 专辑列表 -->
    <view class="album_list">
      <view
        class="album_item"
        v-for="(item, index) in albumList"
        :key="item.id"
      >
     	<!-- 3. 使用组件 传递参数为 list 和 index  -->
        <go-detail
          :list="wallpaper"
          :index="index"
        >
          <image
            mode="aspectFill"
            :src="item.thumb"
          ></image>
        </go-detail>
      </view>
    </view>
  </view>
</template>
<script>
import goDetail from '@/components/goDetail' // 1. 引入组件
export default {
     
     
  components: {
     
      goDetail }, // 2. 注册组件
  data () {
     
     
    return {
     
     
      id: '', // 页面传递过来的id值
      albumList: [] // 专辑列表数据
    }
  },
  onLoad (options) {
     
     
    this.id = options.id
    this.getList()
  },
  methods: {
     
     
    getList () {
     
     
      // 发送请求给 this.albumList 赋值
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
  1. 获取传递的参数并渲染公共组件的页面内容

在 pages 目录下创建 imgDetail/index.vue 文件,内容如下:

<!-- src/pages/imgDetail/index.vue -->
<template>
	<view>
	专辑内容详情-页面渲染遵循vue语法
	</view>
</template>

<script>

export default {
     
     
  data () {
     
     
    return {
     
     
      imgDetail: []  // 图片信息对象
    }
  },
  onLoad () {
     
     
    console.log(getApp().globalData) // 获取App中的全局数据
    const {
     
      imgList, imgIndex } = getApp().globalData
    this.imgDetail = imgList[imgIndex]
  },
  methods: {
     
     }
}
</script>

<style lang="scss" scoped >
</style>

over
作为学习笔记记录一下,以后有好的方法再更新。

猜你喜欢

转载自blog.csdn.net/tyoubinn/article/details/109056204