
需求點.png
動態(tài)的效果圖在文章末尾,有相同需求的可參考思路
在項目的個人模塊中,用戶是可以去修改一些自己的信息數(shù)據(jù)的,比如:更換頭像的上傳...
接下來看下項目的目錄結構,個人中心是單獨的構建的一個目錄文件,而頂部是Layouts的布局結構目錄。

項目目錄結構.png
這種很容易聯(lián)想到Vuex狀態(tài)管理器,因為數(shù)據(jù)共享!如何聯(lián)動?監(jiān)聽!此處監(jiān)聽的是Vuex狀態(tài)管理器。
1、Vuex數(shù)據(jù)存儲定義內容
其中有幾個要素 是組成Vuex的關鍵, state(狀態(tài)) mutations actions ,
state 表示 需要共享的狀態(tài)數(shù)據(jù)
mutations 表示 更改 state的方法集合 只能是同步更新 不能在這里寫一些異步的請求操作
actions 如果需要做異步請求 可以在actions中寫 在這一步驟中做異步的數(shù)據(jù)獲取?。?!一定需要注意的是此處僅僅只是對異步數(shù)據(jù)的獲取,真正的處理操作還是在mutations,actions拿到數(shù)據(jù)然后提交給 mutations后 mutation再做同步更新。
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex)
export default new Vuex.Store({
state: {
imgUrl:'',//存儲頭像的照片url
},
mutations: {
// 同步函數(shù)的處理
// 頭像設置
setImg(state,payload){
state.imgUrl = payload;//將載荷的值給vuex
}
}
})
2、個人中心頭像上傳的操作處理
- 2.1、頭像上傳成功的操作:
這里共執(zhí)行了兩個重要的步驟:一是將上傳到服務器的頭像的url地址存入到會話,因為不存到會話的話,直接使用Vuex的值,用戶刷新頁面的話,頁面的數(shù)據(jù)是會消失的,因為組件重新執(zhí)行了生命周期!,因此先存到緩存。第二個重要步驟就是將更新的頭像的url地址同步更新到Vuex狀態(tài)管理器中去,這樣Layouts中處理監(jiān)聽的時候能夠監(jiān)聽到管理器中的數(shù)據(jù)發(fā)生改變。
<!--頭像上傳-->
<div class="user-photo">
<div class="user-img">
<img :src="headSculpture" alt="" />
</div>
<div class="user-upload">
<el-upload
:before-upload="beforeAvatarUpload"
:on-success="handleAvatarSuccess"
accept=".jpg,.png"
:show-file-list="false"
:action="imgUrl"
>
<el-button size="small" type="primary">修改頭像</el-button>
</el-upload>
</div>
</div>
/* 上傳頭像成功時的回調函數(shù) */
handleAvatarSuccess(res, file) {
this.userForm.headSculpture = res.data.fileIds[0];
postUpdateHeadImg({
// uid: JSON.parse(sessionStorage.getItem("userInfo")).uid,
headSculpture: this.headSculpture,
})
.then((res) => {
if (res.code == 0) {
this.$message({
type: "success",
message: "修改頭像成功",
duration: "1000",
});
// 更新會話內容
sessionStorage.setItem("userInfo", JSON.stringify(this.userForm));
// 獲取新的會話中的內容
this.userForm = JSON.parse(sessionStorage.getItem("userInfo"));
this.$store.commit("setImg", this.userForm.headSculpture);//設置Vuex中的數(shù)據(jù),頭部也要使用共享數(shù)據(jù)
this.headSculpture = this.userForm.headSculpture;
}
})
.catch();
},
3、頭部導航欄的頭像URL監(jiān)聽處理
這里監(jiān)聽到值后只需要將url進行一次賦值即可,因為此時用戶刷新界面的話,數(shù)據(jù)也不會消失,因為當生命周期重新執(zhí)行時,在mounted生命周期中也是會被執(zhí)行一次,會去會話中找尋對應的url地址。
watch:{
'$store.state.imgUrl'(newVal){
this.userImg = newVal;
this.$forceUpdate();// 更新數(shù)據(jù)
}
},
mounted(){
// 初始化頭像
if (sessionStorage.getItem("userInfo")) {
this.userImg = JSON.parse(
sessionStorage.getItem("userInfo")
).headSculpture;
this.user = JSON.parse(sessionStorage.getItem("userInfo")).name;
} else {
// 沒有上傳頭像就使用本地自帶的默認頭像
this.userImg = require("@/assets/admin.png");
}
}
4、大致效果

頭像的聯(lián)動修改.gif