vue3通过js调用组件, 例如 Toast, Message

第一段代码是组件的封装 vue

第二段代码, 是组件调用 js, 对第一段代码的挂载调用

第三段代码, 是页面 vue , 调用 第二段代码的函数, 实现第一段代码的动态挂载, 移除

 

组件内容

<template>
  <transition name="show">
    <div class="m-notice" v-show="showNotice">
      <h2>{{ title }}</h2>
      <div class="m-msg">{{ message }}</div>
    </div>
  </transition>
</template>

<script setup>
import { onMounted, reactive, toRefs } from "vue";

const props = defineProps(["title", "message"]);

const state = reactive({
  showNotice: false,
});

onMounted(() => {
  state.showNotice = true;
});

const { showNotice } = toRefs(state);
</script>

<style lang="scss" scoped>
@keyframes show {
  0% {
    transform: translateX(370px);
  }
  100% {
    transform: translateX(0px);
  }
}

@keyframes hide {
  0% {
    transform: translateX(0px);
  }
  100% {
    transform: translateX(370px);
  }
}

.show-enter-active {
  animation: show 0.3s ease-out;
}

.show-leave-active {
  animation: hide 0.3s ease-in;
}

.show-leave-to {
  opacity: 0;
}

.m-notice {
  position: fixed;
  right: 20px;
  top: 20px;
  width: 330px;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  padding: 12px;
  // animation: show 0.3s ease-out;

  h2 {
    font-size: 16px;
    font-weight: 500;
  }

  .m-msg {
    font-size: 14px;
    color: #606266;
    margin-top: 8px;
  }
}
</style>

 

 

 

 

组件的挂载, vue3去掉了 Vue.extend后的解决办法  .js 文件

import { render, createVNode } from "vue";

import MNotice from "./Notice.vue";

export default function (options = {}) {
  const { duration = 2500, title, message } = options;

  const mountNode = document.createElement("div");
  const hideNotice = () => {
    let laterTime = 2500;
    if (
      duration &&
      Object.prototype.toString.call(duration) === "[object Number]"
    ) {
      laterTime = duration;
    }
    setTimeout(() => {
      document.body.removeChild(mountNode);
    }, laterTime);
  };

  const app = createVNode(MNotice, {
    title,
    message,
  });

  render(app, mountNode);

  document.body.appendChild(mountNode);

  hideNotice();
}

 

 

 

 

页面调用

<template>
  <div>
    <button @click="test">按钮</button>
  </div>
</template>

<script setup>
import mNotice from "@/components/Notice/Notice.js";

function test() {
  mNotice({
    title: "滚犊子",
    message: "我是组件调用传递的文案",
  });
}
</script>

<style lang="scss" scoped></style>

 

 

 

显示效果

 

posted @ 2022-08-01 15:38  深海里的星星i  阅读(1438)  评论(0)    收藏  举报