手動添加vue組件


手寫一個消息提示組件掛載到vue實例,也是偷來的哈哈

//先在components 下新建一個Message.vue組件

//appear 特性設置節點的在初始渲染的過渡
<template>
  <transition name="move" appear="">
    <div class="msg" v-if="visible">{{ message }}</div>
  </transition>
</template>
<script>
export default {
  name: "Message",
  props: {
    message: {
      type: String,
      default: "我是一個消息提示"
    },
    duration: {
      type: Number,
      default: 3000
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      list: ["大中國 yyds"]
    };
  },
  mounted() {
    this.autoClose();
  },
  methods: {
    //自動關閉消息提示組件
    autoClose() {
      if (this.duration !== 0) {
        setTimeout(() => {
          this.close();
        }, this.duration + 800); //800毫秒是過渡動畫的時間
      }
    },
    //關閉組件
    close() {
      //sync 修飾符
      this.$emit("update:visible", false);
    }
  }
};
</script>
<style lang="less" scoped>
.msg {
  position: fixed;
  top: 50px;
  left: 0;
  right: 0;
  width: 20%;
  padding: 5 20px;
  margin: auto;
  height: 40px;
  line-height: 40px;
  border-radius: 18px;
  background-color: #fff;
  font-size: 16px;
  text-align: center;
  color: #000;
  background-color: #2d8cf0;
  //動畫進入時
  &.move-enter,
  &.move-leave-to {
    opacity: 0;
    transform: translateY(-50px);
  }
  //動畫持續時
  &.move-enter-active,
  &.move-leave-active {
    transition: 0.8s linear;
  }
}
</style>

components 下新建message.js 完成掛載

import Vue from 'vue'
import Message from "./Message.vue";

const createMessage = (propsData) => {
  //1.生成組件的構造器  propsData固定參數不可更改
  const Ctor = Vue.extend(Message)
  //2.創建組件實例,並執行掛載
  const vm = new Ctor({
    propsData
  }).$mount();
  //監聽組件關閉事件
  vm.$on('update:visible', flag => {
    vm.visible = flag
  })
  //3.通過原生Dom api的方式把組件的根元素插入到文檔(真實DOM)中
  document.body.appendChild(vm.$el);
  return vm;
}

export {
  createMessage
}

在src下新建plugins文件夾 再建index.js文件完成注冊

import Message from '@/components/Message.vue'
import {
  createMessage
} from '@/components/message'

export default {
  install(Vue) {
    //注冊Message組件
    Vue.component(Message.name, Message)

    //添加原型方法
    Vue.prototype.$message = createMessage
  }
}

最后就是在main.js 文件中引用

import My from './plugins'
Vue.use(My)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM