【问题标题】:Upload image need to refresh using $emit / $on in Vue上传图片需要在 Vue 中使用 $emit / $on 刷新
【发布时间】:2019-10-16 15:53:13
【问题描述】:

我有一个通过axios调用用户数据的方法

// method name getUser()
const user = await axios.get(`/user/${this.id}`)
this.id = user.data.data.id
this.name = user.data.data.name
this.email = user.data.data.email

然后我在挂载中使用它,所以如果用户访问/profile/id 它会加载用户数据

mounted() {
    this.getUser()
}

我尝试上传一张图片,并在图片上传成功后使用全局事件总线发出事件。

this.$event.$emit('IMAGE_UPLOAD')

那就把它也抓到挂载上

mounted () {
// if I remove this it works, but I need to preload the data of the user
this.getUser()
this.$event.$on('IMAGE_UPLOAD', () => {
    this.getUser()
})

}

我的问题是它不会改变图像,这意味着如果我在已安装的内部也调用 this.getUser(),我仍然需要刷新页面。

所以我想知道如何解决这个问题。 谢谢!

【问题讨论】:

  • 我不认为它是重复的,因为问题是关于如何解决不重新加载页面以查看图像上传更改的问题。
  • 您确认您的事件处理程序正在被调用吗?是否重新加载相同的图像 ID?
  • 是的,它被调用了。当我在mounted上注释掉this.getUser()上的电话时,它工作正常。
  • 我需要在访问个人资料时显示数据,然后如果用户单击图像,将弹出一个模式,用户可以在其中拖放图像,然后一旦完成图像应该显示新上传的图像。

标签: vue.js events vuejs2 emit


【解决方案1】:

由于上传新图片时图片的url和名称没有改变,所以浏览器中的图片没有更新。所以我过去做的是一个小技巧,通过添加一个唯一的查询参数来从本质上改变图像的 url。因此,使用数据属性作为用户图像的位置,并在更新用户数据的方法中更新 img url 并添加一些独特的查询参数。我通常使用new Date().getTime()。所以你最终会得到类似/img/user-xxxx.png?1559289852686

data(){
   userImg: '/img/user-xxxx.png'
},
methods:{
   getUser(){
     //... get your user data
     .then((data)=>{
         this.userImg = data.user.img +'?'+ new Date().getTime();
     })
}

【讨论】:

    猜你喜欢
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-25
    • 2019-04-18
    • 2018-05-28
    • 1970-01-01
    • 2014-03-29
    相关资源
    最近更新 更多