vue 公共js 文件无法使用 this 解决方案

前言:
在把前端公共的功能放到公共的js 文件里的时候,无法使用 this 去引用已经全局注册的组件和 this本身都是 unfinished

解决之前:

调用处:

 test() {
      // 测试没有this
      myDialog();
    },

具体方法:

//弹出对话框
function myDialogno() {
    this.$alert(
        "测试this",
        "猫",
        {
            confirmButtonText: "确定",
        }
    );
}
// 将全局公共方法,组合成一个对象,并暴露出去
export default {
    myDialogno
}

解决之后:

调用处:

 test() {
      // 测试没有this
      var that = this;
      sendThis(that);
      myDialog();
    },

具体方法:

 //用来获取 调用此js的vue组件实例(this)
let vm = null;
const sendThis = (_this)=>{
    vm = _this;
};

//弹出对话框
function myDialog() {
    vm.$alert(
        "测试this",
        "猫",
        {
            confirmButtonText: "确定",
        }
    );
}
// 将全局公共方法,组合成一个对象,并暴露出去
export default {
    sendThis,//暴露函数
    myDialog
}

解决思路:

可以模仿后端的set 方法给属性赋值,所以可以在公共的js 文件里声明一个vm 的属性和setThis (_this) 方法给 公共的js 里的 属性 vm 赋值,这样this可以作为参数被传递(中心思想,还是把this 对象当做参数传递)。

posted @ 2022-07-31 17:25  康世行  阅读(2056)  评论(0编辑  收藏  举报