Vue插件与Vue组件

plugin插件(插件需要创建一个js文件和一个vue文件)

1、插件是一个对象,必须实现install方法

2、插件需要在vue文件中使用Vue.use(插件)

3、插件方法:

Vue.extend(.vue文件) 继承.vue文件的构造函数

var ToastCom = Vue.extend(ToastVue);

instance.$mount(dom) 手动挂载

instance.$mount(document.createElement("div"));

将插件挂载到全局(所有组件的实例都将拥有插件的方法和属性)

Vue.prototype.$toast = Toast

 js整体代码

//01 导入组件
import ToastVue from './ToastCom.vue'
//定义一个插件 他是一个对象
var Toast = {}
//Vue的插件必须实现install方法
Toast.install = function (Vue) {
    //02 获取组件的构造函数
    var ToastCom = Vue.extend(ToastVue);
    //03 创建组件的实例
    var instance = new ToastCom();
    //04 挂载到真实的dom
    instance.$mount(document.createElement("div"));
    //05 插入到body
    document.body.appendChild(instance.$el);
    //06 关联Toast
    Toast.show = instance.show;
    Toast.hide = instance.hide;

    //把当前对象挂载到Vue的原型上
    //Vue所有的组件和实例都可以使用$toast
    Vue.prototype.$toast = Toast;
}

//导出插件
export default Toast;

vue文件(加载提示插件)

<template>
  <div class="toast" v-if="msg">
    {
   
   { msg }}
  </div>
</template>

<script>
//当文本msg为空的时候 提示隐藏,有文本的时候显示
export default {
  data() {
    return {
      msg: "",
    }; //提示文本
  },
  methods: {
    show(str = "加载中...", delay = 2000) {
      this.msg = str;
      //等待2秒隐藏
      setTimeout(() => {
        this.hide();
      }, delay);
    },
    hide() {
      this.msg = "";
    },
  },
};
</script>

<style scoped="scoped">
.toast {
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  padding: 10px;
  border-radius: 4px;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.4);
}
</style>

插件的使用

1、在main.js中导入插件

 2、在网页中使用

<template>
  <div class="about">
    <button @click="$toast.show('加载中...')">点我</button>
  </div>
</template>

<script>
</script>

 可以结合axios使用

vue组件

定义组件

定义一个组件,命名必须用驼峰式写法或短横线分隔命名,如:CloseSelf.vue与close-self.vue

使用组件

1、导入组件

import CloseSelf from "@/components/CloseSelf.vue"
//@为src

2、注册组件

  components: { CloseSelf },

3、使用组件

<CloseSelf :visible="showAd" @update:visible="showAd = $event">
      //showAd需要data中定义
      <div>
        <img src="../assets/logo.png" />
        <p>上客户端,专享优惠</p>
        <div class="open">打开APP</div>
      </div>
</CloseSelf>

参数传递

猜你喜欢

转载自blog.csdn.net/weixin_48345246/article/details/127351777