美文网首页
vue自定义toast组件

vue自定义toast组件

作者: 李小_包 | 来源:发表于2019-02-26 11:37 被阅读0次

    在手机端项目开发中一些框架的toast兼容性不太好,还需要进行单独修改,并且可定制性不强,一旦遇到需要特定的toast样式还是需要重构样式,这就很尴尬了
    toast组件用到了vue的render函数构建
    1、在components项目文件夹下边新建一个.vue的文件,作为组件(子组件)
    (1.1)在data中定义三个变量

    data() {
      return {
        showToast: false, // 用来控制toast是否显示
        toastContent: '', // toast中显示的内容
        num: 0 // 这个是用来计数,防止用户连续点击出现setTimeout重复调用导致用户体验差
      }
    }
    

    (1.2)在props中定义一个父组件传来的top,用来自定义toast距离顶部的位置,后边的单位是百分比

    props: {
      top: {
        type: [String, Number],
        required: true,
        default: 50
      },
    },
    

    (1.3)在methods中定义一个函数toastShow

    // 轻提示函数,value传入提示文字,time显示时间
    toastShow(value, time) {
      this.num = this.num + 1 // 计次的num+1防止连点
      if(this.num < 2) {
        this.showToast = true // toast显示
        this.toastContent = value  // toast中内容进行赋值
        setTimeout(() => {
          this.showToast = false
          this.num = 0
        }, time)
      }
    }
    

    (1.4)下面创建一个render函数,构建toast样式

    render: function(createElement) {
      return createElement(
        'div', {
            'class': {
            'my-toast': this.showToast
          },
          'attrs': {
            style: `top: ${this.top}%` // 这里是获取父组件传过来的top值默认定义的是50在中间,
          },
          domProps: {
            innerHTML: this.toastContent // 这一步的作用是解析传过来的toast内容中的字符串中的HTML标签主要是解析换行标签
          },
        },
      )
    }
    

    (1.5)最后定义一下toast的样式,可以根据自己的需求情况自定义

    .my-toast {
      white-space: nowrap;
      position: fixed;
      top: 50%;
      left: 50%;
      display: flex;
      color: #fff;
      font-size: 14px;
      line-height: 20px;
      border-radius: 4px;
      align-items: center;
      flex-direction: column;
      box-sizing: border-box;
      -webkit-transform: translate3d(-50%, -50%, 0);
      background-color: rgba(0, 0, 0, .7);
      padding: 0.1rem 0.2rem;
      z-index: 999;
      text-align: center;
    }
    

    2、在父组件中引入
    (2.1)引入组件toast

    import toast from '**************************'
    

    (2.2)注册组件toast

    components: {
      toast,
    },
    

    (2.3)在页面中引入toast组件

    <toast class="toast-father" ref="childToast" :top="toast_top"></toast>
    <!--toast-father的样式可以定义为fixed的定位出视图-->
    <!--ref是用来父组件获取子组件的方法-->
    <!--这里在父组件的data中需要定义一个toast_top用来控制toast的位置-->
    

    (2.4.1)最后在需要的地方调用toast

    this.$refs.childToast.toastShow(`************`, 2000)
    // 第一个参数是toast中展示的内容,第二个是定义toast显示的时间
    

    (2.4.2)最后在需要的地方调用toast(子组件toast内容可以解析HTML标签)

    this.$refs.childToast.toastShow(`******<br/>******`, 2000)
    //<br/>标签可以被解析进行换行
    

    相关文章

      网友评论

          本文标题:vue自定义toast组件

          本文链接:https://www.haomeiwen.com/subject/fgaoyqtx.html