vueVue技术vue

插件方式的组件封装

2021-07-31  本文已影响0人  大佬教我写程序

步骤(以创建一个Toast)

<template >
  <div class="toast">
    <div>{{message}}</div>
  </div>
</template>
<script>
export default {
  name:"Toast",
  data() {
    return {
      message:'',
      isShow:false
    }
  },
  methods: {
    show(message = "message",duration=2000){
    this.isShow = true
    this.message = message
    setTimeout(()=>{
      this.isShow = false
    this.message = ''
    },duration)
  }
  },
}
</script>
<style scoped>
  .toast{
    position: fixed;
    top: 50%;
    left: 50%;
    color: #fff;
    background-color: rgba(0, 0, 0, 0.5);
  }
</style>
import Toast from './Toast.vue'
 
const obj = {}
 
obj.install = function(Vue){
  //创建组件构造器
  const toastContrustor = Vue.extend(Toast)
  //new的方式,根据组件构造器,可以创建出来一个组件对象
  const toast  = new toastContrustor()
  //将组建对象手动挂载到某一元素上
  toast.$mount(document.createElement('div'))
  //toast.$el对应的就是对应的div上的
  document.body.appendChild(toast.$el)
  
  Vue.prototype.$toast = toast
}
export default obj
import Toast from 'components/common/Toast/index.js'
 
Vue.use(Toast)
new Vue({
  render: h => h(App),
  router,
  store
  
}).$mount('#app')
this.$toast.show(res,2000)
上一篇下一篇

猜你喜欢

热点阅读