vue的實現方法
1、寫一個Toast組件
Toast.vue
<template>
<div class="toast" v-if="show">
<div class="box">
<div class="title">{{title}}</div>
<div class="content">{{content}}</div>
<div class="btn" @click="callback()">{{btn}}</div>
</div>
</div>
</template>
<script>
export default {
name: "Toast",
data() {
return {
show: true
};
}
};
</script>
<style scoped>
.toast {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index: 99;
font-size: 14px;
}
.box {
height: 130px;
width: 240px;
border: 1px solid #ccc;
border-radius: 4px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
.title,
.content {
line-height: 30px;
padding: 0 10px;
}
.title {
color: #666;
border-bottom: 1px solid #ccc;
}
.btn {
display: inline-block;
padding: 4px 10px;
color: gray;
border: 1px solid #ccc;
border-radius: 2px;
position: absolute;
bottom: 10px;
left: 50%;
transform: translate(-50%);
cursor: pointer;
}
</style>
組件中除了擁有是否展現自身的show屬性以外其他屬性都沒有被定義,這些屬性將在下面的toast.js中通過Vue.extend出來的實例構造器的實例化對象傳入。
Vue.extend 返回的是一個“擴展實例構造器”,也就是一個預設了部分選項的 Vue 實例構造器
var myVue = Vue.extend({
// 預設選項 -- 等下我們會把Toast組件作爲預設傳入
}) // 返回一個“擴展實例構造器”
// 然後就可以這樣來使用
var vm = new myVue({
// 其他選項
})
2、 寫一個toast.js
toast.js
import Toast from './Toast.vue'
import Vue from 'vue'
let ToastCmp = Vue.extend(Toast)
function toast(options) {
let div = document.createElement('div')
document.body.appendChild(div)
let { title, content, btn, callback } = options || {}
new ToastCmp({
data() {
return {
title: title || "Tips",
content: content || "contents here",
btn: btn || "confirm",
callback: () => {
callback && callback instanceof Function && callback()
this.show = false
}
}
}
}).$mount(div)
}
export default {
install: (Vue) => {
Vue.prototype.$toast = toast
}
}
3、將toast方法掛載上Vue的原型然後調用即可
react的實現方法
1、寫一個toast.js
樣式與vue的一樣,此處省略
toast.js
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
class Toast extends Component {
constructor(props) {
super(props)
}
render() {
const { title, content, btn, callback } = this.props
return (
<div className="toast">
<div className="box">
<div className="title">{title}</div>
<div className="content">{content}</div>
<div className="btn" onClick={callback}>{btn}</div>
</div>
</div>
)
}
}
export default options => {
let { title, content, btn, callback } = options || {}
let div = document.createElement('div')
document.body.appendChild(div)
ReactDOM.render(React.createElement(Toast, {
title: title || "Tips",
content: content || "contents here",
btn: btn || "confirm",
callback: () => {
callback && callback instanceof Function && callback()
document.body.removeChild(div)
}
}), div)
}