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

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

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

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

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

@ -81,6 +81,16 @@ export default {
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) {
state.settings.user = user;
},

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

@ -4,10 +4,38 @@ import store from "@/store";
export function doLogout() {
logout();
// 移除前端本地用来认证登录的字段
Cookies.remove("loginMode");
// 网易云的接口会自动移除该 cookies
// Cookies.remove("MUSIC_U");
// 更新状态仓库中的用户信息
store.commit("updateUser", { id: 0 });
// 更新状态仓库中的登录状态
store.commit("updateLogout");
}
// MUSIC_U 只有在账户登录的情况下才有
export function isLoggedIn() {
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";
export function isTrackPlayable(track) {
@ -7,7 +7,7 @@ export function isTrackPlayable(track) {
reason: "",
};
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;
} else {
result.playable = false;

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

@ -112,9 +112,9 @@ export default {
NProgress.done();
},
methods: {
...mapMutations(["updateUser", "updateUserInfo"]),
...mapMutations(["updateUser", "updateUserInfo", "updateAccountLogin"]),
afterLogin() {
// Cookies.set("MUSIC_U", true, { expires: 3650 });
this.updateAccountLogin(true);
Cookies.set("loginMode", "account", { expires: 3650 });
userPlaylist({
uid: this.$store.state.settings.user.userId,
@ -127,9 +127,7 @@ export default {
this.$router.push({ path: "/library" });
});
},
login() {
this.processing = true;
if (this.mode === "phone") {
validatePhone() {
if (
this.countryCode === "" ||
this.phone === "" ||
@ -137,8 +135,26 @@ export default {
) {
alert("国家区号、手机或密码不正确");
this.processing = false;
return;
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() {
this.processing = true;
if (this.mode === "phone") {
this.processing = this.validatePhone();
loginWithPhone({
countrycode: this.countryCode.replace("+", "").replace(/\s/g, ""),
phone: this.phoneNumber.replace(/\s/g, ""),
@ -156,16 +172,7 @@ export default {
alert(error);
});
} else {
let 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("邮箱或密码不正确");
this.processing = false;
return;
}
this.processing = this.validateEmail();
loginWithEmail({
email: this.email.replace(/\s/g, ""),
password: "fakePassword",

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

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

Loading…
Cancel
Save