参照
https://juejin.cn/post/6867798692460494861
v
文件目录如上
index.js
import Toast from './toast.vue'
Toast.install = (Vue) => {
Vue.prototype.$toast = (msg, duration) => { //添加一个实例方法 这样全局的实例都可以调用$toast方法了 msg、duration是调用$toast时传入的两个参数
if (!msg) {
return;
}
duration = duration || 1500; //如果不传toast持续时间则默认使用此时间
const constroct = Vue.extend(Toast) //构造器
const instance = new constroct(); //创建实例
instance.msg = msg || ''; //将$toast(msg,duration)中的msg传入组件的data中
const tpl = instance.$mount().$el //vue实例未挂载时可这样拿到它的dom 后续可对它的dom进行操作
document.querySelector('body').appendChild(tpl);
setTimeout(() => {
document.querySelector('body').removeChild(tpl)
}, duration);
}
}
export default Toast;
toast.vue
<template>
<div class="toast">{{msg}}</div>
</template>
<script>
export default {
name: "Toast",
data() {
return {
msg: ""
};
}
};
</script>
<style scoped>
.toast {
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: fit-content;
height: 44px;
background-color: rgba(0, 0, 0);
display: flex;
justify-content: center;
align-items: center;
padding-left: 10px;
padding-right: 10px;
color: #fff;
border-radius: 5px;
}
</style>
pakage.json
{
"name": "/* toast-component11 */",
"version": "3.0.9",
"description": "",
"main": "dist/toast.js",
"scripts": {
"build": "webpack --mode production"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.11.5",
"@babel/preset-env": "^7.11.5",
"babel-loader": "^8.1.0",
"css-loader": "^4.2.2",
"style-loader": "^1.2.1",
"vue-loader": "^15.9.3",
"vue-template-compiler": "^2.6.12",
"webpack": "^4.44.1",
"webpack-cli": "^3.3.12"
}
}
先登录
npm ERR! Unexpected token < in JSON at position 0 while parsing near ‘<!DOCTYPE HTML P
运行
// 顺序执行如下代码即可
npm config get proxy
npm config get https-proxy
npm config set registry https://registry.npmjs.org
yarn add toast-component11
或者 npm install toast-component11
main.js
import Toast from 'toast-component11'
Vue.use(Toast)
组件中使用
<template>
<div class="hello">
<div @click="showToast">点我出toast</div>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
},
data() {
return {
}
},
methods: {
showToast() {
this.$toast('hello world', 2000)
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="stylus">
</style>