关于前端:Vueextend实现弹窗组件

5次阅读

共计 1613 个字符,预计需要花费 5 分钟才能阅读完成。

文中默认对 vue/cli 曾经了解。写该文章是版本为 4.x

实现弹窗组件

在 components 文件中 新建一个 notice 文件夹 cd notice
新建一个 Notice.vue

<template>
    <div class="notice" v-if="isShow">
        <h4>{{title}}</h4>
        <p>{{content}}</p>
    </div>
</template>

<script>
    export default {
        name: 'Notice',
        props: {
            title: {  
                type: String,
                default: ''
            },
            content: {
                type: String,
                default: ''
            },
            duration: {
                type: Number,
                default: 2000   // 默认 2 秒后隐没
            }
        },
        data () {
            return {isShow: false,}
        },
        methods: {hide() {
                this.isShow = false;
                this.remove();    //  组件销毁}
        },
        mounted () {
            this.isShow = true;
            setTimeout(this.hide,this.duration)
        }
    }
</script>

<style lang="scss" scoped>
.notice {
    width: 200px;
    border: 1px solid #333;
    padding: 10px;
    position: absolute;
    right: 0;
}

</style>

新建一个 index.js 文件 次要是组件实例的创立性能

import Vue from 'vue'
import Notice from './Notice.vue'
const NoticeController = Vue.extend(Notice)
function notice(options) {
    const nc = new NoticeController({propsData: options  // propsData 用于值得传递});
    nc.$mount();  // 挂载
    document.body.appendChild(nc.$el);  // 插入 body 当中
    nc.remove = function () {   //  该办法用于销毁实例
        document.body.removeChild(nc.$el);
        nc.$destroy()}
    console.log(nc);
    return nc;
}

export default notice

次要性能根本都实现
抉择就是用于页面的实现的成果了

第一步 把组件实例注册全局中 main.js

import notice from './components/notice/index'
Vue.prototype.$notice = notice

第二步,创立一个用于实现弹窗的按钮 组件 XButton.vue

<template>
    <div>
        <button @click="click"> 告诉信息按钮 </button>
    </div>
</template>

<script>
    export default {
        methods: {click() {this.$emit('click')
            }
        },
    }
</script>

第三步,把这个按钮组件挂载某个页面上 比如说:home.vue

<template>
  <div class="home">
    <x-button @click="open"></x-button>
  </div>
</template>

<script>
// @ is an alias to /src
import XButton from '@/components/XButton.vue'

export default {
  name: 'Home',
  components: {XButton},
  methods: {open() {
      this.$notice({
        title: 'xuwen',
        content: '123'
      })
    }
  },
}
</script>

整一个弹窗的组件实现了,该弹窗组件是以 element ui 中的弹窗组件 为原型实现的

正文完
 0