feat: using vuex to make login status reactively (#51)

master
Hawtim Zhang 4 years ago committed by GitHub
parent 5ce9c3689a
commit 780b429fa9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -3,7 +3,8 @@ import request from "@/utils/request";
import { mapTrackPlayableStatus } from "@/utils/common"; import { mapTrackPlayableStatus } from "@/utils/common";
/** /**
* 获取音乐 url * 获取音乐 url
* 说明 : 使用歌单详情接口后 , 能得到的音乐的 id, 但不能得到的音乐 url, 调用此接口, 传入的音乐 id( 可多个 , 用逗号隔开 ), 可以获取对应的音乐的 url,未登录状态返回试听片段(返回字段包含被截取的正常歌曲的开始时间和结束时间) * 说明 : 使用歌单详情接口后 , 能得到的音乐的 id, 但不能得到的音乐 url, 调用此接口, 传入的音乐 id( 可多个 , 用逗号隔开 ), 可以获取对应的音乐的 url,
* !!!未登录状态返回试听片段(返回字段包含被截取的正常歌曲的开始时间和结束时间)
* @param {string} id - 音乐的 id例如 id=405998841,33894312 * @param {string} id - 音乐的 id例如 id=405998841,33894312
*/ */
export function getMP3(id) { export function getMP3(id) {

@ -36,7 +36,8 @@
</span> </span>
</div> </div>
</div> </div>
<div class="like-button" v-show="isLoggedIn"> <!-- 账号登录才会显示 like 图标 -->
<div class="like-button" v-show="accountLogin">
<button-icon <button-icon
@click.native="likeCurrentSong" @click.native="likeCurrentSong"
:title="$t('player.like')" :title="$t('player.like')"
@ -118,7 +119,7 @@
<script> <script>
import { updateMediaSessionMetaData } from "@/utils/mediaSession"; import { updateMediaSessionMetaData } from "@/utils/mediaSession";
import { mapState, mapMutations, mapActions } from "vuex"; import { mapState, mapMutations, mapActions } from "vuex";
import { isLoggedIn } from "@/utils/auth"; import { isAccountLoggedIn } from "@/utils/auth";
import { userLikedSongsIDs } from "@/api/user"; import { userLikedSongsIDs } from "@/api/user";
import { likeATrack } from "@/api/track"; import { likeATrack } from "@/api/track";
import "@/assets/css/slider.css"; import "@/assets/css/slider.css";
@ -144,14 +145,14 @@ export default {
setInterval(() => { setInterval(() => {
this.progress = ~~this.howler.seek(); this.progress = ~~this.howler.seek();
}, 1000); }, 1000);
if (this.isLoggedIn) { if (isAccountLoggedIn()) {
userLikedSongsIDs(this.settings.user.userId).then((data) => { userLikedSongsIDs(this.settings.user.userId).then((data) => {
this.updateLikedSongs(data.ids); this.updateLikedSongs(data.ids);
}); });
} }
}, },
computed: { computed: {
...mapState(["player", "howler", "settings", "liked"]), ...mapState(["player", "howler", "settings", "liked", "accountLogin"]),
currentTrack() { currentTrack() {
return this.player.currentTrack; return this.player.currentTrack;
}, },
@ -174,9 +175,6 @@ export default {
let max = ~~(this.currentTrack.dt / 1000); let max = ~~(this.currentTrack.dt / 1000);
return max > 1 ? max - 1 : max; return max > 1 ? max - 1 : max;
}, },
isLoggedIn() {
return isLoggedIn();
},
}, },
methods: { methods: {
...mapMutations([ ...mapMutations([

@ -60,7 +60,7 @@
<div></div> <div></div>
</div> </div>
<div class="actions" v-if="!isTracklist"> <div class="actions" v-if="!isTracklist">
<button v-if="isLoggedIn" @click="likeThisSong"> <button v-if="accountLogin" @click="likeThisSong">
<svg-icon <svg-icon
icon-class="heart" icon-class="heart"
:style="{ :style="{
@ -78,7 +78,7 @@
</template> </template>
<script> <script>
import { isLoggedIn } from "@/utils/auth"; import { mapState } from "vuex";
import ArtistsInLine from "@/components/ArtistsInLine.vue"; import ArtistsInLine from "@/components/ArtistsInLine.vue";
import ExplicitSymbol from "@/components/ExplicitSymbol.vue"; import ExplicitSymbol from "@/components/ExplicitSymbol.vue";
@ -93,6 +93,7 @@ export default {
return { focus: false, trackStyle: {} }; return { focus: false, trackStyle: {} };
}, },
computed: { computed: {
...mapState(["accountLogin"]),
imgUrl() { imgUrl() {
if (this.track.al !== undefined) return this.track.al.picUrl; if (this.track.al !== undefined) return this.track.al.picUrl;
if (this.track.album !== undefined) return this.track.album.picUrl; if (this.track.album !== undefined) return this.track.album.picUrl;
@ -127,9 +128,6 @@ export default {
if (this.isPlaying) trackClass.push("playing"); if (this.isPlaying) trackClass.push("playing");
return trackClass; return trackClass;
}, },
isLoggedIn() {
return isLoggedIn();
},
}, },
methods: { methods: {
goToAlbum() { goToAlbum() {

@ -3,7 +3,7 @@ import VueRouter from "vue-router";
import store from "@/store"; import store from "@/store";
import NProgress from "nprogress"; import NProgress from "nprogress";
import "@/assets/css/nprogress.css"; import "@/assets/css/nprogress.css";
import Cookies from "js-cookie"; import { isLooseLoggedIn } from "@/utils/auth";
NProgress.configure({ showSpinner: false, trickleSpeed: 100 }); NProgress.configure({ showSpinner: false, trickleSpeed: 100 });
@ -12,7 +12,7 @@ const routes = [
{ {
path: "/", path: "/",
name: "home", name: "home",
component: () => import("@/views/home"), component: () => import("@/views/home.vue"),
meta: { meta: {
keepAlive: true, keepAlive: true,
}, },
@ -20,32 +20,32 @@ const routes = [
{ {
path: "/login", path: "/login",
name: "login", name: "login",
component: () => import("@/views/login"), component: () => import("@/views/login.vue"),
}, },
{ {
path: "/login/username", path: "/login/username",
name: "loginUsername", name: "loginUsername",
component: () => import("@/views/loginUsername"), component: () => import("@/views/loginUsername.vue"),
}, },
{ {
path: "/login/account", path: "/login/account",
name: "loginAccount", name: "loginAccount",
component: () => import("@/views/loginAccount"), component: () => import("@/views/loginAccount.vue"),
}, },
{ {
path: "/playlist/:id", path: "/playlist/:id",
name: "playlist", name: "playlist",
component: () => import("@/views/playlist"), component: () => import("@/views/playlist.vue"),
}, },
{ {
path: "/album/:id", path: "/album/:id",
name: "album", name: "album",
component: () => import("@/views/album"), component: () => import("@/views/album.vue"),
}, },
{ {
path: "/artist/:id", path: "/artist/:id",
name: "artist", name: "artist",
component: () => import("@/views/artist"), component: () => import("@/views/artist.vue"),
meta: { meta: {
keepAlive: true, keepAlive: true,
}, },
@ -53,12 +53,12 @@ const routes = [
{ {
path: "/mv/:id", path: "/mv/:id",
name: "mv", name: "mv",
component: () => import("@/views/mv"), component: () => import("@/views/mv.vue"),
}, },
{ {
path: "/next", path: "/next",
name: "next", name: "next",
component: () => import("@/views/next"), component: () => import("@/views/next.vue"),
meta: { meta: {
keepAlive: true, keepAlive: true,
}, },
@ -66,17 +66,17 @@ const routes = [
{ {
path: "/search", path: "/search",
name: "search", name: "search",
component: () => import("@/views/search"), component: () => import("@/views/search.vue"),
}, },
{ {
path: "/new-album", path: "/new-album",
name: "newAlbum", name: "newAlbum",
component: () => import("@/views/newAlbum"), component: () => import("@/views/newAlbum.vue"),
}, },
{ {
path: "/explore", path: "/explore",
name: "explore", name: "explore",
component: () => import("@/views/explore"), component: () => import("@/views/explore.vue"),
meta: { meta: {
keepAlive: true, keepAlive: true,
}, },
@ -84,7 +84,7 @@ const routes = [
{ {
path: "/library", path: "/library",
name: "library", name: "library",
component: () => import("@/views/library"), component: () => import("@/views/library.vue"),
meta: { meta: {
requireLogin: true, requireLogin: true,
keepAlive: true, keepAlive: true,
@ -93,7 +93,7 @@ const routes = [
{ {
path: "/library/liked-songs", path: "/library/liked-songs",
name: "likedSongs", name: "likedSongs",
component: () => import("@/views/playlist"), component: () => import("@/views/playlist.vue"),
meta: { meta: {
requireLogin: true, requireLogin: true,
}, },
@ -101,7 +101,7 @@ const routes = [
{ {
path: "/settings", path: "/settings",
name: "settings", name: "settings",
component: () => import("@/views/settings"), component: () => import("@/views/settings.vue"),
}, },
]; ];
const router = new VueRouter({ const router = new VueRouter({
@ -116,17 +116,15 @@ const router = new VueRouter({
}); });
router.beforeEach((to, from, next) => { router.beforeEach((to, from, next) => {
// 需要登录的逻辑
if (to.meta.requireLogin) { if (to.meta.requireLogin) {
if (store.state.settings.user.nickname === undefined) { if (store.state.settings.user.nickname === undefined) {
next({ path: "/login" }); next({ path: "/login" });
} }
if ( if (isLooseLoggedIn()) {
Cookies.get("MUSIC_U") === undefined &&
Cookies.get("loginMode") === "account"
) {
next({ path: "/login" });
} else {
next(); next();
} else {
next({ path: "/login" });
} }
} else { } else {
next(); next();

@ -1,6 +1,6 @@
import { updateMediaSessionMetaData } from "@/utils/mediaSession"; import { updateMediaSessionMetaData } from "@/utils/mediaSession";
import { getTrackDetail, scrobble, getMP3 } from "@/api/track"; import { getTrackDetail, scrobble, getMP3 } from "@/api/track";
import { isLoggedIn } from "@/utils/auth"; import { isAccountLoggedIn } from "@/utils/auth";
import { updateHttps } from "@/utils/common"; import { updateHttps } from "@/utils/common";
export default { export default {
@ -41,8 +41,7 @@ export default {
dispatch("nextTrack"); dispatch("nextTrack");
}); });
} }
if (isAccountLoggedIn()) {
if (isLoggedIn) {
getMP3(track.id).then((data) => { getMP3(track.id).then((data) => {
// 未知情况下会没有返回数据导致报错,增加防范逻辑 // 未知情况下会没有返回数据导致报错,增加防范逻辑
if (data.data[0]) { if (data.data[0]) {

@ -81,6 +81,16 @@ export default {
return track; return track;
}); });
}, },
updateAccountLogin(state, status) {
state.accountLogin = status;
},
updateUsernameLogin(state, status) {
state.usernameLogin = status;
},
updateLogout() {
this.commit("updateAccountLogin", false);
this.commit("updateUsernameLogin", false);
},
updateUser(state, user) { updateUser(state, user) {
state.settings.user = user; state.settings.user = user;
}, },

@ -9,4 +9,6 @@ export default {
}, },
player: JSON.parse(localStorage.getItem("player")), player: JSON.parse(localStorage.getItem("player")),
settings: JSON.parse(localStorage.getItem("settings")), settings: JSON.parse(localStorage.getItem("settings")),
accountLogin: false,
usernameLogin: false,
}; };

@ -4,10 +4,38 @@ import store from "@/store";
export function doLogout() { export function doLogout() {
logout(); logout();
// 移除前端本地用来认证登录的字段
Cookies.remove("loginMode"); Cookies.remove("loginMode");
// 网易云的接口会自动移除该 cookies
// Cookies.remove("MUSIC_U");
// 更新状态仓库中的用户信息
store.commit("updateUser", { id: 0 }); store.commit("updateUser", { id: 0 });
// 更新状态仓库中的登录状态
store.commit("updateLogout");
} }
// MUSIC_U 只有在账户登录的情况下才有
export function isLoggedIn() { export function isLoggedIn() {
return Cookies.get("MUSIC_U") !== undefined ? true : false; return Cookies.get("MUSIC_U") !== undefined ? true : false;
} }
// 账号登录
export function isAccountLoggedIn() {
return (
Cookies.get("MUSIC_U") !== undefined &&
Cookies.get("loginMode") === "account"
);
}
// 用户名搜索(用户数据为只读)
export function isUsernameLoggedIn() {
return (
Cookies.get("MUSIC_U") === undefined &&
Cookies.get("loginMode") === "username"
);
}
// 账户登录或者用户名搜索都判断为登录,宽松检查
export function isLooseLoggedIn() {
return isAccountLoggedIn() || isUsernameLoggedIn();
}

@ -1,4 +1,4 @@
import { isLoggedIn } from "./auth"; import { isAccountLoggedIn } from "./auth";
import store from "@/store"; import store from "@/store";
export function isTrackPlayable(track) { export function isTrackPlayable(track) {
@ -7,7 +7,7 @@ export function isTrackPlayable(track) {
reason: "", reason: "",
}; };
if (track.fee === 1 || track.privilege?.fee === 1) { if (track.fee === 1 || track.privilege?.fee === 1) {
if (isLoggedIn && store.state.settings.user.vipType === 11) { if (isAccountLoggedIn() && store.state.settings.user.vipType === 11) {
result.playable = true; result.playable = true;
} else { } else {
result.playable = false; result.playable = false;

@ -60,8 +60,8 @@
More by More by
<router-link :to="`/artist/${album.artist.id}`" <router-link :to="`/artist/${album.artist.id}`"
>{{ album.artist.name }} >{{ album.artist.name }}
</router-link></div </router-link>
> </div>
<div> <div>
<CoverRow <CoverRow
type="album" type="album"

@ -112,9 +112,9 @@ export default {
NProgress.done(); NProgress.done();
}, },
methods: { methods: {
...mapMutations(["updateUser", "updateUserInfo"]), ...mapMutations(["updateUser", "updateUserInfo", "updateAccountLogin"]),
afterLogin() { afterLogin() {
// Cookies.set("MUSIC_U", true, { expires: 3650 }); this.updateAccountLogin(true);
Cookies.set("loginMode", "account", { expires: 3650 }); Cookies.set("loginMode", "account", { expires: 3650 });
userPlaylist({ userPlaylist({
uid: this.$store.state.settings.user.userId, uid: this.$store.state.settings.user.userId,
@ -127,18 +127,34 @@ export default {
this.$router.push({ path: "/library" }); this.$router.push({ path: "/library" });
}); });
}, },
validatePhone() {
if (
this.countryCode === "" ||
this.phone === "" ||
this.password === ""
) {
alert("国家区号、手机或密码不正确");
this.processing = false;
return false;
}
return true;
},
validateEmail() {
const emailReg = /^[A-Za-z0-9]+([_][A-Za-z0-9]+)*@([A-Za-z0-9]+\.)+[A-Za-z]{2,6}$/;
if (
this.email === "" ||
this.password === "" ||
!emailReg.test(this.email)
) {
alert("邮箱或密码不正确");
return false;
}
return true;
},
login() { login() {
this.processing = true; this.processing = true;
if (this.mode === "phone") { if (this.mode === "phone") {
if ( this.processing = this.validatePhone();
this.countryCode === "" ||
this.phone === "" ||
this.password === ""
) {
alert("国家区号、手机或密码不正确");
this.processing = false;
return;
}
loginWithPhone({ loginWithPhone({
countrycode: this.countryCode.replace("+", "").replace(/\s/g, ""), countrycode: this.countryCode.replace("+", "").replace(/\s/g, ""),
phone: this.phoneNumber.replace(/\s/g, ""), phone: this.phoneNumber.replace(/\s/g, ""),
@ -156,16 +172,7 @@ export default {
alert(error); alert(error);
}); });
} else { } else {
let emailReg = /^[A-Za-z0-9]+([_][A-Za-z0-9]+)*@([A-Za-z0-9]+\.)+[A-Za-z]{2,6}$/; this.processing = this.validateEmail();
if (
this.email === "" ||
this.password === "" ||
!emailReg.test(this.email)
) {
alert("邮箱或密码不正确");
this.processing = false;
return;
}
loginWithEmail({ loginWithEmail({
email: this.email.replace(/\s/g, ""), email: this.email.replace(/\s/g, ""),
password: "fakePassword", password: "fakePassword",

@ -41,8 +41,9 @@
<ButtonTwoTone <ButtonTwoTone
@click.native="confirm" @click.native="confirm"
v-show="activeUser.nickname !== undefined" v-show="activeUser.nickname !== undefined"
>{{ $t("login.confirm") }}</ButtonTwoTone
> >
{{ $t("login.confirm") }}
</ButtonTwoTone>
</div> </div>
</div> </div>
</template> </template>
@ -73,7 +74,7 @@ export default {
NProgress.done(); NProgress.done();
}, },
methods: { methods: {
...mapMutations(["updateUser", "updateUserInfo"]), ...mapMutations(["updateUser", "updateUserInfo", "updateUsernameLogin"]),
search() { search() {
if (!this.keyword) return; if (!this.keyword) return;
search({ keywords: this.keyword, limit: 9, type: 1002 }).then((data) => { search({ keywords: this.keyword, limit: 9, type: 1002 }).then((data) => {
@ -83,6 +84,7 @@ export default {
}, },
confirm() { confirm() {
this.updateUser(this.activeUser); this.updateUser(this.activeUser);
this.updateUsernameLogin(true);
Cookies.set("loginMode", "username", { expires: 3650 }); Cookies.set("loginMode", "username", { expires: 3650 });
userPlaylist({ userPlaylist({
uid: this.activeUser.userId, uid: this.activeUser.userId,

@ -46,7 +46,7 @@
</ButtonTwoTone> </ButtonTwoTone>
<ButtonTwoTone <ButtonTwoTone
v-if=" v-if="
isLoggedIn && playlist.creator.userId !== settings.user.userId accountLogin && playlist.creator.userId !== settings.user.userId
" "
shape="round" shape="round"
:iconClass="playlist.subscribed ? 'heart-solid' : 'heart'" :iconClass="playlist.subscribed ? 'heart-solid' : 'heart'"
@ -92,7 +92,6 @@ import NProgress from "nprogress";
import { getPlaylistDetail, subscribePlaylist } from "@/api/playlist"; import { getPlaylistDetail, subscribePlaylist } from "@/api/playlist";
import { playAList } from "@/utils/play"; import { playAList } from "@/utils/play";
import { getTrackDetail } from "@/api/track"; import { getTrackDetail } from "@/api/track";
import { isLoggedIn } from "@/utils/auth";
import ButtonTwoTone from "@/components/ButtonTwoTone.vue"; import ButtonTwoTone from "@/components/ButtonTwoTone.vue";
import TrackList from "@/components/TrackList.vue"; import TrackList from "@/components/TrackList.vue";
@ -132,10 +131,7 @@ export default {
window.removeEventListener("scroll", this.handleScroll, true); window.removeEventListener("scroll", this.handleScroll, true);
}, },
computed: { computed: {
...mapState(["player", "settings"]), ...mapState(["player", "settings", "accountLogin"]),
isLoggedIn() {
return isLoggedIn();
},
isLikeSongsPage() { isLikeSongsPage() {
return this.$route.name === "likedSongs"; return this.$route.name === "likedSongs";
}, },

Loading…
Cancel
Save