vue3 之app.config.globalProperties的简单使用

vue3 之app.config.globalProperties的简单使用

main.js中

//一个简单对图片的处理
app.config.globalProperties.$filters = {
    
    
  preImg(url) {
    
    
    if (url && url.startsWith('http')) {
    
    
      return url
    } else {
    
    
      url = `http://www.baidu.com${
      
      url}`
      return url
    }
  }
}

组件中使用

<img :src="$filters.preImg(ImgUrl)" alt="" >

当在组件内想要调用preImg方法时,可以用getCurrentInstance()来实现

import {
    
     getCurrentInstance, onMounted } from "vue";
export default {
    
    
  setup( ) {
    
    
    const {
    
     that } = getCurrentInstance(); // 获取上下文实例,that等同于vue2中的this
    onMounted(() => {
    
    
      that.preImg();
    });
  },
};

但是现在发现有个问题在正式环境里面that获取不到路由和全局挂载对象的,可以用proxy来代替

import {
    
     getCurrentInstance, onMounted } from "vue";
export default {
    
    
  setup( ) {
    
    
    const {
    
     proxy } = getCurrentInstance(); 
    onMounted(() => {
    
    
      proxy.preImg();
    });
  },
};

猜你喜欢

转载自blog.csdn.net/weixin_45324044/article/details/123138169