一般状况使用vue时都是挂在某个节点下,例如:
App.vuehtml
<body>
<div id="app"></div>
</body>
复制代码
main.jsvue
import Vue from "vue";
import App from "./App.vue";
new Vue({
render: h => h(App)
}).$mount("#app");
复制代码
借助webpack vue-loader App.vue将会导出成一个对象App,h函数将App数据渲染成节点再挂载到#app节点下。至此全部页面操做都在该节点下,包括路由跳转等等。
可是有时候咱们也可能须要将节点挂载在其余位置,而非#app上,或者说须要多个能够挂载vue的节点。
例如咱们须要开发一个相似element-ui的通知组件webpack
<!--这里假设组件名称为alert-->
<alert :show="isShow"></alert>
复制代码
咱们须要的是这样调用组件:web
this.$Alert({content:'hello',duration:2})
复制代码
<body>
<!-- vue渲染区域-->
<div id="app"></div>
<!--alert组件渲染区,而且为fixed定位-->
<div class="alert"></div>
</body>
复制代码
因此咱们须要第二个区域使用vue了,Vue提供了extend API 能够拓展vue实例。 例如在main.js中element-ui
new Vue({
router,
store,
render: h => h(App)
}).$mount("#app");
const Tips = Vue.extend({
template: `<h1>{{message}}</h1>`,
data() {
return {
message: "hello,world"
};
}
});
const comp = new Tips().$mount();
document.body.appendChild(comp.$el);
复制代码
上述代码便可在渲染出第二块区域h1,在h1内同样可使用vue
因此开发思路以下:bash
main.js 注册$Alert()app
import { info } from "./components/alert.js";
Vue.prototype.$Alert = info;
复制代码
alert.js函数
import Vue from "vue";
import Alert from "./alert.vue";
// 向Alert组件传递data数据
export const info = options => {
const Instance = new Vue({
render(h) {
return h(Alert, {
props: options
});
}
});
const comp = Instance.$mount();
document.body.appendChild(comp.$el);
const alert = Instance.$children[0];
alert.add(options);
};
复制代码
alert.vue优化
<template>
<div class="alert">
<div class="alert-main" v-for="item in notices" :key="item.name">
<div class="alert-content">{{ item.content }}</div>
</div>
</div>
</template>
<script>
import { setTimeout } from "timers";
let seed = 0;
function getUuid() {
return `alert_${seed++}`;
}
export default {
data() {
return {
notices: []
};
},
methods: {
add(notice) {
const uuid = getUuid();
let _notice = Object.assign({ name: uuid }, notice);
this.notices.push(_notice);
const { duration } = _notice;
setTimeout(() => {
this.remove(_notice.name);
}, duration * 1000);
},
remove(name) {
alert(name);
const notices = this.notices;
for (let i = 0; i < notices.length; i++) {
if (notices[i].name === name) {
this.notices.splice(i, 1);
break;
}
}
}
}
};
</script>
<style>
.alert {
position: fixed;
width: 100%;
top: 16px;
left: 0;
text-align: center;
pointer-events: none;
}
.alert-content {
display: inline-block;
padding: 8px 16px;
background: #fff;
border-radius: 3px;
box-shadow: 0 1px 6px rgba(0, 0, 0, 0.2);
margin-bottom: 8px;
}
</style>
复制代码
具体页面使用:ui
this.$Alert({
content: "这是一条提示信息",
duration: 3
});
复制代码
一个最原始的alert组件就实现了,后续可自行优化!