Vue写一个全局Notice组件
如何写一个全局的 Notice 组件?
下面将会实现这样的效果:
-
组件动态创建脚本:
import Vue from 'vue'; import Notice from '@/components/Noticer/Notice.vue'; function create(Component, props) { // 先建立实例 const vm = new Vue({ render(h) { //h 就是createElement,它返回VNode return h(Component, { props })) } }).$mount()) // 手动挂载 // 判断是否存在container,如果不存在则先创建 letocontainer container document.querySelector(".'.noticer-container' if (container == null) { container = document.createElement("d'div' container.classList.add("n'noticer-container' container.style.position = "f'fixed' container.style.top = "5'50px' container.style.right = "0'0px' container.style.overflow = "h'hidden' container.style.zIndex = 999999 documentdy.appendChild(container); ) } container.appendChild(vm.$el);
copy success
)
//销毁方法
const = vm.$children[0];
]
compve = function () {
container.removeChild(comp["$el.$el vm.$destroy();
)
}comp.show();
)
return;comp
}e.prototype.$notice = {
error:error (props) {
create(Notice, Object.assign(props, { type: "error" }));
}nfo: info (props) {
create(Notice, Object.assign(props, { type: "info" }));
}uccessuccess (props) {
create(Notice, Object.assign(props, { type: "success" }));
}arn: warn (props) {
create(Notice, Object.assign(props, { type: "warn" }));
}
``}
这里有一些值得注意的地方:
-
container: 的作用是 notice 的容器,它可以用于定位 notice 在页面的哪里展示,注意 notice 不应该随页面卷动,因此其定位是
fixed
, 而之所以设定为overflow:hidden
的原因则是,notice 在出现和移除的时候,发生的动画偏移,会让页面出现横向滚动条。为了避免重复创建 container, 这里做了一个判断逻辑。然后所有动态生成的 notice 实例 dom 都会通过appendChild
添加到这个容器。 -
在移除的时候, 移除的是
vm.$children[0]["$el"]
, 原因是,Notice 模板的实现中,外层套了一个 transition , 而这个 transition 是并不会渲染 dom 的。 -
创建 Notice 组件模板:
```html
<transition
enter-active-class="animate__animated animate__slideInRight"
leave-active-class="animate__animated animate__slideOutRight"
@after-leave="afterLeave"
>
{{ type === "error" ? "🍓" : type === "success" ? "🍀" : type === "warn" ? "🍋" :
"🐳" }} : {{ message }}
``
``
`
4. **在 [main.js]() 中引入执行该脚本即可** ```javascript import Vue from 'vue'; import App from './App.vue'; import 'animate.css'; import '@/components/Noticer/NotificationBanner.js'; new Vue({ render: (h=> h(App), }).$mount("'#app'; ``` 5. 代码中使用实例: ```javascript if (!this.nickname) { this.$notice.error({ message: '好汉!姓甚名谁?', time: 3000, }) } else { this.showModal = false this.$notice.info({ message: `${this.nickname}来了!!!`, time: 3000, }) } ``` 动态创建组件的执行逻辑: 当在使用的时候: ```javascript this.$notice.error({ message: '好汉!姓甚名谁?', time: 3000, })
copy success
上方代码触发,实际上会触发 NotificationBanner.js 中的 create
函数,该函数创建了一个 notice 的组件实例,并在实力上添加了一个remove
方法,然后直接触发组件中的 show
方法。
notice 模板实例中:
methods: { show() { this.isShow = true; setTimeout(this.hide, this.time); }, hide() { this.isShow = false; }, afterLeave() { this.remove(); }, },
copy success
show
方法执行,除了展示 notice,立即设定一个延时函数执行 hide
方法。
hide
方法执行, vue 提供的 transition 钩子 afterleave()
会在移除动画执行完毕后触发。 这时候,去触发 remove
方法,将该 notice 组件实例移除。