vue使用install函数把组件做成插件方便全局调用

1.首先新建一个Cmponent.vue文件

<template>
  <div class="toast" v-show="isShow">
    <div>{{ message }}</div>
  </div>
</template>

<script>
export default {
  name: "",
  data() {
    return {
      message: "",
      isShow: false,
    };
  },
  methods: {
    show(message, duration) {
      this.isShow = true;
      this.message = message;

      setTimeout(() => {
        this.isShow = false;
        this.message = '';
      }, duration);
    },
  },
};
</script>

<style scoped>
.toast {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 8px 10px;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.75);
  z-index: 999;
  border: 1px solid #000;
  border-radius: 8px;
}
</style>

2.其次在同一目录下建立index.js文件,在这个文件中使用install方法来全局注册该组件

import Toast from './Toast.vue'

const obj = {}

obj.install = function (Vue) {
  // 1创建组件构造器
  const toastContrustor = Vue.extend(Toast)

  // 2.通过new的方式,根据组件构造器,可以创建出来一个组件对象
  const toast = new toastContrustor()

  // 3.将组件对象手动挂载到某一个元素上
  toast.$mount(document.createElement('div'))

  // 4.toast.$el对应的就是div
  document.body.appendChild(toast.$el)

  // Vue.component('toast', obj)

  // 在vue原型上添加$toast,方便以后组件使用
  Vue.prototype.$toast = toast;
}

export default obj

3.在main.js文件中 安装toast插件

// 只要在index.js里规定了install方法,就可以向其他ui组件库那样,使用Vue.use()来全局使用

//main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

import toast from 'components/common/toast'

// 安装toast插件
Vue.use(toast);

Vue.prototype.$bus = new Vue()
// app.mount('#app')
new Vue({
  render: h => h(App),
  router,
  store
}).$mount('#app')

4.在组件中使用

// detail组件中使用,部分代码
this.addCart(product).then(res => {
   // console.log(res);
   this.$toast.show(res,2000);
})
addCart(context, payload) {
    return new Promise((resolve, reject) => {
      // 1.查找之前数组中是否有该商品
      let oldProduct = context.state.cartList.find(item => item.iid === payload.iid)

      // 2.判断oldproduct
      if (oldProduct) {
        // oldProduct.count += 1
        context.commit(ADD_COUNTER, oldProduct)
        resolve('当前商品数量+1')
      } else {
        payload.count = 1
        // context.state.cartList.push(payload)
        context.commit(ADD_TO_CART, payload)
        resolve('添加了新的商品')
      }
    })
  }
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值