vue笔记(四)原组件重写

这里记录下对Element UI走马灯组件的重写,增加一个点击图片跳转对应页面的功能。

思路是:重写的子组件使用Element UI走马灯组件代码,将参数设置为由父组件传递,然后增加所需功能。

一、

先来大致看一下Element UI走马灯组件,这里给出地址:http://element-cn.eleme.io/#/zh-CN/component/carousel

二、

新建父组件和子组件文件,笔者使用工具是WebStorm,分别在对应路径下新建即可。

三、

Element UI走马灯组件代码复制到子组件,代码如下:

<template>
  <el-carousel :interval="4000" type="card" height="200px">
    <el-carousel-item v-for="item in 6" :key="item">
      <h3>{{ item }}</h3>
    </el-carousel-item>
  </el-carousel>
</template>

<style>
  .el-carousel__item h3 {
    color: #475669;
    font-size: 14px;
    opacity: 0.75;
    line-height: 200px;
    margin: 0;
  }
  
  .el-carousel__item:nth-child(2n) {
    background-color: #99a9bf;
  }
  
  .el-carousel__item:nth-child(2n+1) {
    background-color: #d3dce6;
  }
</style>

然后读懂组件代码,删除不必要的样式代码。

四、

将子组件所需数据改为由父组件传递,使用props,子组件代码如下:

<template>
  <el-carousel
    :interval="interval"
    :type="type"
    :height="imgHeight"
    :autoplay="autoplay"
  >
    <el-carousel-item
      name=""
      :label="label"
      :imgList="imgList"
      v-for="(image,imgIndex) in imgList" :key="imgIndex">
      <router-link :to="image.toUrl"><img :src="image.url"/></router-link>

    </el-carousel-item>
  </el-carousel>
</template>

<script>
    export default {
        name: "Broadcast",
        props:{
          imgHeight:{
            default: '300px'
          },
          type:{
            default:''
          },
          interval:{
            default:4000
          },
          autoplay:{
            default:true
          },
          label:{
            default:''
          },
          imgList:{
            type: Array,
            required:true
          }

        },
        data(){
          return{

          }
        }
    }
</script>

<style scoped>
  .el-carousel__item img {
    width: 100%;
    height: 100%;
  }
</style>

说明:

:type等 : 开头的,通过数据绑定来获取数据,将绑定的变量设置在props内,则可以通过父组件的同名变量来获取值。

v-for的格式是 xx in yy 前者是自定义变量为其中一组数据,后者是具体数据组,一般是数组,xx可以增加一项成为(xx1,xx2)的格式,对应为(value,key)。

:key是为了高效的遍历,建议添加,值建议为遍历数据的id

五、

父组件传递数据,进行测试,代码如下:

<template>
  <div>
    <Broadcast
      imgHeight="300px"
      type="card"
      :imgList="imgList"
    ></Broadcast>
  </div>
</template>

<script>
import Broadcast from "../components/Broadcast";
export default {
  components: {Broadcast},
  data(){
    return{
      imgList:[
        {
          url:'static/img/01.jpg',
          toUrl:'/demo-index'
        },
        {
          url:'static/img/02.jpg',
          toUrl:'/demo-index'
        },
        {
          url:'static/img/03.jpg',
          toUrl:'/demo-index'
        },
        {
          url:'static/img/04.jpg',
          toUrl:'/demo-index'
        },
      ],
    }
  }

}
</script>

<style scoped>

</style>

效果如下:

走马灯:


点击图片后,路径变化:


猜你喜欢

转载自blog.csdn.net/gcc_java/article/details/80941991