美文网首页
vue组件封装

vue组件封装

作者: 曹锦花 | 来源:发表于2019-08-12 13:42 被阅读0次

    下面的这个组件,将原生的按钮 button 进行了封装,如果传入了 prop: to,那它会渲染为一个 <a> 标签,用于打开这个链接地址,如果没有传入 to,就当作普通 button 使用。

    <!-- button.vue -->
    <template>
      <component :is="tagName" v-bind="tagProps">
        <slot></slot>
      </component>
    </template>
    <script>
      export default {
        props: {
          // 链接地址
          to: {
            type: String,
            default: ''
          },
          // 链接打开方式,如 _blank
          target: {
            type: String,
            default: '_self'
          }
        },
        computed: {
          // 动态渲染不同的标签
          tagName () {
            return this.to === '' ? 'button' : 'a';
          },
          // 如果是链接,把这些属性都绑定在 component 上
          tagProps () {
            let props = {};
    
            if (this.to) {
              props = {
                target: this.target,
                href: this.to
              }
            }
    
            return props;
          }
        }
      }
    </script>
    

    使用组件:

    <template>
      <div>
        <i-button>普通按钮</i-button>
        <br>
        <i-button to="https://juejin.im">链接按钮</i-button>
        <br>
        <i-button to="https://juejin.im" target="_blank">新窗口打开链接按钮</i-button>
      </div>
    </template>
    <script>
      import iButton from '../components/a.vue';
    
      export default {
        components: { iButton }
      }
    </script>
    

    相关文章

      网友评论

          本文标题:vue组件封装

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