Personal settings (four) - Modify avatar - upload pictures plan: axios + formdata & use http-request attribute to override the default upload & Brothers application components by value

04- Personal settings - Modify avatar

  • Modify avatar picture requests submitted by way of patch
  • The default submit el-upload component approach is post
  • You can not use the default upload method, upload custom.
    • Request upload pictures of themselves need to be sent.
      • Upload pictures big event program: xhr + formdata
      • Dark Horse headlines upload pictures program: axios + formdata
  • Use http-request attribute to override the default upload
    • Is designated function, when you select a picture trigger

src / views / setting / index.vue the div box

 <el-upload
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            :http-request="upload"
          >
            <img v-if="userInfo.photo" :src="userInfo.photo" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>

Upload

src / views / setting / index.vue of methods in

 // 当你选择了图片后触发  有传参
    async upload (result) {
      // console.log(result.file) 就是选中的图片
      // 通过axios和formdata提交图片
      const formData = new FormData()   //初始化数据
      // 往formData追加图片  
      formData.append('photo', result.file)
      const { data: { data } } = await this.$http.patch('user/photo', formData)
      // 上传成功
      this.$message.success('修改头像成功')
      // 预览
      this.userInfo.photo = data.photo
      // 更新本地存储的头像
      const user = store.getUser()
      user.photo = data.photo
      store.setUser(user)
      // 更新Home组件的头像
        //第三步:script下引入eventbus包  之后,谁传数据,谁用eventbus触发事件
      eventBus.$emit('updatePhoto', data.photo)
    },

home component binding event: views / home.vue

eventBus.$on('updatePhoto', (photo) => {
    // 绑定事件 接受头像数据   第二步:谁要数据,谁用eventbus绑定事件
      this.photo = photo
    })
Published 74 original articles · won praise 1 · views 1364

Guess you like

Origin blog.csdn.net/weixin_44867717/article/details/104403639