前端项目TS化

pull/6/head
orzi! 2 years ago
parent a2bbc29cc5
commit cc74a0beea

@ -22,3 +22,6 @@ dist-ssr
*.njsproj *.njsproj
*.sln *.sln
*.sw? *.sw?
package-lock.json
components.d.ts

@ -10,7 +10,7 @@
<body> <body>
<div id="app"></div> <div id="app"></div>
<script type="module" src="/src/main.js"></script> <script type="module" src="/src/main.ts"></script>
</body> </body>
</html> </html>

@ -29,7 +29,10 @@
"vuex": "^4.0.2" "vuex": "^4.0.2"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^17.0.35",
"@vitejs/plugin-vue": "^2.3.1", "@vitejs/plugin-vue": "^2.3.1",
"@vue/compiler-sfc": "^3.2.36",
"typescript": "^4.7.2",
"vite": "^2.9.2" "vite": "^2.9.2"
} }
} }

@ -35,7 +35,7 @@
</n-config-provider> </n-config-provider>
</template> </template>
<script setup> <script setup lang="ts">
import { computed } from 'vue'; import { computed } from 'vue';
import { useStore } from 'vuex'; import { useStore } from 'vuex';
import { darkTheme } from 'naive-ui'; import { darkTheme } from 'naive-ui';

@ -8,12 +8,12 @@ import request from '@/utils/request';
* - @param {string} password * - @param {string} password
* @returns Promise * @returns Promise
*/ */
export const userLogin = (params = {}) => { export const userLogin = (params: NetParams.AuthUserLogin = {}) => {
return request({ return request({
method: 'post', method: 'post',
url: '/auth/login', url: '/auth/login',
data: params, data: params,
}); }) as unknown as Promise<NetReq.AuthUserLogin>;
}; };
/** /**
@ -53,7 +53,7 @@ export const userInfo = (token = '') => {
* - @param {string} old_password * - @param {string} old_password
* @returns Promise * @returns Promise
*/ */
export const updateUserPassword = data => { export const updateUserPassword = (data: any) => {
return request({ return request({
method: 'post', method: 'post',
url: '/api/user/password', url: '/api/user/password',

@ -5,12 +5,12 @@ import request from '@/utils/request';
* @param {Object} params * @param {Object} params
* @returns Promise * @returns Promise
*/ */
export const getPosts = params => { export const getPosts = (params: any) => {
return request({ return request({
method: 'get', method: 'get',
url: '/posts', url: '/posts',
params params
}); }) as unknown as Promise<NetReq.PostGetPosts>;
}; };
/** /**
@ -18,7 +18,7 @@ export const getPosts = params => {
* @param {Object} params * @param {Object} params
* @returns Promise * @returns Promise
*/ */
export const getTags = params => { export const getTags = (params: any) => {
return request({ return request({
method: 'get', method: 'get',
url: '/tags', url: '/tags',
@ -31,7 +31,7 @@ export const getTags = params => {
* @param {Object} params * @param {Object} params
* @returns Promise * @returns Promise
*/ */
export const getPost = params => { export const getPost = (params: any) => {
return request({ return request({
method: 'get', method: 'get',
url: '/post', url: '/post',
@ -44,7 +44,7 @@ export const getPost = params => {
* @param {Object} params * @param {Object} params
* @returns Promise * @returns Promise
*/ */
export const getPostStar = params => { export const getPostStar = (params: any) => {
return request({ return request({
method: 'get', method: 'get',
url: '/post/star', url: '/post/star',
@ -57,7 +57,7 @@ export const getPostStar = params => {
* @param {Object} data * @param {Object} data
* @returns Promise * @returns Promise
*/ */
export const postStar = data => { export const postStar = (data: any) => {
return request({ return request({
method: 'post', method: 'post',
url: '/post/star', url: '/post/star',
@ -70,7 +70,7 @@ export const postStar = data => {
* @param {Object} params * @param {Object} params
* @returns Promise * @returns Promise
*/ */
export const getPostCollection = params => { export const getPostCollection = (params: any) => {
return request({ return request({
method: 'get', method: 'get',
url: '/post/collection', url: '/post/collection',
@ -83,7 +83,7 @@ export const getPostCollection = params => {
* @param {Object} data * @param {Object} data
* @returns Promise * @returns Promise
*/ */
export const postCollection = data => { export const postCollection = (data: any) => {
return request({ return request({
method: 'post', method: 'post',
url: '/post/collection', url: '/post/collection',
@ -96,7 +96,7 @@ export const postCollection = data => {
* @param {Object} params * @param {Object} params
* @returns Promise * @returns Promise
*/ */
export const getPostComments = params => { export const getPostComments = (params: any) => {
return request({ return request({
method: 'get', method: 'get',
url: '/post/comments', url: '/post/comments',
@ -112,7 +112,7 @@ export const getPostComments = params => {
* - @param {array} tags * - @param {array} tags
* @returns Promise * @returns Promise
*/ */
export const createPost = data => { export const createPost = (data: any) => {
return request({ return request({
method: 'post', method: 'post',
url: '/post', url: '/post',
@ -126,7 +126,7 @@ export const createPost = data => {
* - @param {number} id * - @param {number} id
* @returns Promise * @returns Promise
*/ */
export const deletePost = data => { export const deletePost = (data: any) => {
return request({ return request({
method: 'delete', method: 'delete',
url: '/post', url: '/post',
@ -140,7 +140,7 @@ export const deletePost = data => {
* - @param {number} id * - @param {number} id
* @returns Promise * @returns Promise
*/ */
export const lockPost = data => { export const lockPost = (data: any) => {
return request({ return request({
method: 'post', method: 'post',
url: '/post/lock', url: '/post/lock',
@ -155,7 +155,7 @@ export const lockPost = data => {
* - @param {array} users at * - @param {array} users at
* @returns Promise * @returns Promise
*/ */
export const createComment = data => { export const createComment = (data: any) => {
return request({ return request({
method: 'post', method: 'post',
url: '/post/comment', url: '/post/comment',
@ -169,7 +169,7 @@ export const createComment = data => {
* - @param {number} id * - @param {number} id
* @returns Promise * @returns Promise
*/ */
export const deleteComment = data => { export const deleteComment = (data: any) => {
return request({ return request({
method: 'delete', method: 'delete',
url: '/post/comment', url: '/post/comment',
@ -185,7 +185,7 @@ export const deleteComment = data => {
* - @param {number} at_user_id atID * - @param {number} at_user_id atID
* @returns Promise * @returns Promise
*/ */
export const createCommentReply = data => { export const createCommentReply = (data: any) => {
return request({ return request({
method: 'post', method: 'post',
url: '/post/comment/reply', url: '/post/comment/reply',
@ -199,7 +199,7 @@ export const createCommentReply = data => {
* - @param {number} id ID * - @param {number} id ID
* @returns Promise * @returns Promise
*/ */
export const deleteCommentReply = data => { export const deleteCommentReply = (data: any) => {
return request({ return request({
method: 'delete', method: 'delete',
url: '/post/comment/reply', url: '/post/comment/reply',

@ -5,7 +5,7 @@ import request from '@/utils/request';
* @param {Object} params * @param {Object} params
* @returns Promise * @returns Promise
*/ */
export const getCaptcha = params => { export const getCaptcha = (params: any) => {
return request({ return request({
method: 'get', method: 'get',
url: '/captcha', url: '/captcha',
@ -18,7 +18,7 @@ export const getCaptcha = params => {
* @param {Object} data * @param {Object} data
* @returns Promise * @returns Promise
*/ */
export const sendCaptcha = data => { export const sendCaptcha = (data: any) => {
return request({ return request({
method: 'post', method: 'post',
url: '/captcha', url: '/captcha',
@ -31,7 +31,7 @@ export const sendCaptcha = data => {
* @param {Object} data * @param {Object} data
* @returns Promise * @returns Promise
*/ */
export const bindUserPhone = data => { export const bindUserPhone = (data: any) => {
return request({ return request({
method: 'post', method: 'post',
url: '/user/phone', url: '/user/phone',
@ -44,7 +44,7 @@ export const bindUserPhone = data => {
* @param {Object} data * @param {Object} data
* @returns Promise * @returns Promise
*/ */
export const changePassword = data => { export const changePassword = (data: any) => {
return request({ return request({
method: 'post', method: 'post',
url: '/user/password', url: '/user/password',
@ -57,7 +57,7 @@ export const changePassword = data => {
* @param {Object} data * @param {Object} data
* @returns Promise * @returns Promise
*/ */
export const changeNickname = data => { export const changeNickname = (data: any) => {
return request({ return request({
method: 'post', method: 'post',
url: '/user/nickname', url: '/user/nickname',
@ -70,7 +70,7 @@ export const changeNickname = data => {
* @param {Object} data * @param {Object} data
* @returns Promise * @returns Promise
*/ */
export const changeAvatar = data => { export const changeAvatar = (data: any) => {
return request({ return request({
method: 'post', method: 'post',
url: '/user/avatar', url: '/user/avatar',
@ -83,7 +83,7 @@ export const changeAvatar = data => {
* @param {Object} params * @param {Object} params
* @returns Promise * @returns Promise
*/ */
export const getUnreadMsgCount = params => { export const getUnreadMsgCount = (params: any) => {
return request({ return request({
method: 'get', method: 'get',
url: '/user/msgcount/unread', url: '/user/msgcount/unread',
@ -96,7 +96,7 @@ export const getUnreadMsgCount = params => {
* @param {Object} params * @param {Object} params
* @returns Promise * @returns Promise
*/ */
export const getMessages = params => { export const getMessages = (params: any) => {
return request({ return request({
method: 'get', method: 'get',
url: '/user/messages', url: '/user/messages',
@ -109,7 +109,7 @@ export const getMessages = params => {
* @param {Object} data * @param {Object} data
* @returns Promise * @returns Promise
*/ */
export const readMessage = data => { export const readMessage = (data: any) => {
return request({ return request({
method: 'post', method: 'post',
url: '/user/message/read', url: '/user/message/read',
@ -122,12 +122,12 @@ export const readMessage = data => {
* @param {Object} params * @param {Object} params
* @returns Promise * @returns Promise
*/ */
export const getCollections = params => { export const getCollections = (params: any) => {
return request({ return request({
method: 'get', method: 'get',
url: '/user/collections', url: '/user/collections',
params params
}); }) as unknown as Promise<NetReq.UserGetCollections>;
}; };
/** /**
@ -135,7 +135,7 @@ export const getCollections = params => {
* @param {Object} params * @param {Object} params
* @returns Promise * @returns Promise
*/ */
export const getStars = params => { export const getStars = (params: any) => {
return request({ return request({
method: 'get', method: 'get',
url: '/user/stars', url: '/user/stars',
@ -148,7 +148,7 @@ export const getStars = params => {
* @param {Object} params * @param {Object} params
* @returns Promise * @returns Promise
*/ */
export const getUserProfile = params => { export const getUserProfile = (params: any) => {
return request({ return request({
method: 'get', method: 'get',
url: '/user/profile', url: '/user/profile',
@ -161,7 +161,7 @@ export const getUserProfile = params => {
* @param {Object} params * @param {Object} params
* @returns Promise * @returns Promise
*/ */
export const getUserPosts = params => { export const getUserPosts = (params: any) => {
return request({ return request({
method: 'get', method: 'get',
url: '/user/posts', url: '/user/posts',
@ -174,7 +174,7 @@ export const getUserPosts = params => {
* @param {Object} params * @param {Object} params
* @returns Promise * @returns Promise
*/ */
export const getBills = params => { export const getBills = (params: any) => {
return request({ return request({
method: 'get', method: 'get',
url: '/user/wallet/bills', url: '/user/wallet/bills',
@ -187,7 +187,7 @@ export const getBills = params => {
* @param {Object} data * @param {Object} data
* @returns Promise * @returns Promise
*/ */
export const reqRecharge = data => { export const reqRecharge = (data: any) => {
return request({ return request({
method: 'post', method: 'post',
url: '/user/recharge', url: '/user/recharge',
@ -200,7 +200,7 @@ export const reqRecharge = data => {
* @param {Object} params * @param {Object} params
* @returns Promise * @returns Promise
*/ */
export const getRecharge = params => { export const getRecharge = (params: any) => {
return request({ return request({
method: 'get', method: 'get',
url: '/user/recharge', url: '/user/recharge',
@ -213,12 +213,12 @@ export const getRecharge = params => {
* @param {Object} params * @param {Object} params
* @returns Promise * @returns Promise
*/ */
export const getSuggestUsers = params => { export const getSuggestUsers = (params: {k: string}) => {
return request({ return request({
method: 'get', method: 'get',
url: '/suggest/users', url: '/suggest/users',
params params
}); }) as unknown as Promise<NetReq.UserGetSuggestUsers>;
}; };
/** /**
@ -226,12 +226,12 @@ export const getSuggestUsers = params => {
* @param {Object} params * @param {Object} params
* @returns Promise * @returns Promise
*/ */
export const getSuggestTags = params => { export const getSuggestTags = (params: {k: string}) => {
return request({ return request({
method: 'get', method: 'get',
url: '/suggest/tags', url: '/suggest/tags',
params params
}); }) as unknown as Promise<NetReq.UserGetSuggestTags>;
}; };
/** /**
@ -239,7 +239,7 @@ export const getSuggestTags = params => {
* @param {Object} params * @param {Object} params
* @returns Promise * @returns Promise
*/ */
export const precheckAttachment = params => { export const precheckAttachment = (params: any) => {
return request({ return request({
method: 'get', method: 'get',
url: '/attachment/precheck', url: '/attachment/precheck',
@ -252,7 +252,7 @@ export const precheckAttachment = params => {
* @param {Object} params * @param {Object} params
* @returns Promise * @returns Promise
*/ */
export const getAttachment = params => { export const getAttachment = (params: any) => {
return request({ return request({
method: 'get', method: 'get',
url: '/attachment', url: '/attachment',

@ -79,7 +79,7 @@
message: '', message: '',
}, },
{ {
validator(rule, value) { validator(rule: FormItemRule, value: any) {
return ( return (
!!registerForm.password && !!registerForm.password &&
registerForm.password.startsWith( registerForm.password.startsWith(
@ -137,30 +137,31 @@
</n-modal> </n-modal>
</template> </template>
<script setup> <script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'; import { ref, reactive, onMounted } from 'vue';
import { useStore } from 'vuex'; import { useStore } from 'vuex';
import { userLogin, userRegister, userInfo } from '@/api/auth'; import { userLogin, userRegister, userInfo } from '@/api/auth';
import type { FormInst, FormItemRule } from 'naive-ui';
const store = useStore(); const store = useStore();
const loading = ref(false); const loading = ref(false);
const loginRef = ref(null); const loginRef = ref<FormInst>();
const loginForm = reactive({ const loginForm = reactive({
username: '', username: '',
password: '', password: '',
}); });
const registerRef = ref(null); const registerRef = ref<FormInst>();
const registerForm = reactive({ const registerForm = reactive({
username: '', username: '',
password: '', password: '',
repassword: '', repassword: '',
}); });
const handleLogin = (e) => { const handleLogin = (e: Event) => {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
loginRef.value?.validate((errors) => { loginRef.value?.validate(errors => {
if (!errors) { if (!errors) {
loading.value = true; loading.value = true;
@ -191,7 +192,7 @@ const handleLogin = (e) => {
}); });
}; };
const handleRegister = (e) => { const handleRegister = (e: Event) => {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();

@ -97,7 +97,7 @@
</div> </div>
</template> </template>
<script setup> <script setup lang="ts">
import { ref, computed } from 'vue'; import { ref, computed } from 'vue';
import { useStore } from 'vuex'; import { useStore } from 'vuex';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
@ -113,12 +113,9 @@ const replyAtUsername = ref('');
const replyComposeRef = ref(); const replyComposeRef = ref();
const emit = defineEmits(['reload']); const emit = defineEmits(['reload']);
const props = defineProps({ const props = withDefaults(defineProps<{
comment: { comment: Item.CommentProps
type: Object, }>(), {})
default: () => {},
},
});
const comment = computed(() => { const comment = computed(() => {
let comment = Object.assign( let comment = Object.assign(
@ -127,8 +124,8 @@ const comment = computed(() => {
imgs: [], imgs: [],
}, },
props.comment props.comment
); ) as {texts: Item.CommentProps[], imgs: Item.CommentProps[]} & Item.CommentProps;
comment.contents.map((content) => { comment.contents.map((content :any) => {
if (+content.type === 1 || +content.type === 2) { if (+content.type === 1 || +content.type === 2) {
comment.texts.push(content); comment.texts.push(content);
} }
@ -139,9 +136,10 @@ const comment = computed(() => {
return comment; return comment;
}); });
const doClickText = (e, id) => { const doClickText = (e: MouseEvent, id: number | string) => {
if (e.target.dataset.detail) { let _target = e.target as any;
const d = e.target.dataset.detail.split(':'); if (_target.dataset.detail) {
const d = _target.dataset.detail.split(':');
if (d.length === 2) { if (d.length === 2) {
store.commit('refresh'); store.commit('refresh');
if (d[0] === 'tag') { if (d[0] === 'tag') {
@ -158,7 +156,7 @@ const doClickText = (e, id) => {
} }
}; };
const focusReply = (reply) => { const focusReply = (reply: Item.ReplyProps) => {
replyAtUserID.value = reply.user_id; replyAtUserID.value = reply.user_id;
replyAtUsername.value = reply.user?.username || ''; replyAtUsername.value = reply.user?.username || '';
replyComposeRef.value?.switchReply(true); replyComposeRef.value?.switchReply(true);

@ -154,7 +154,7 @@
</template> </template>
<script setup> <script setup lang="ts">
import { onMounted, ref } from 'vue'; import { onMounted, ref } from 'vue';
import { useStore } from 'vuex'; import { useStore } from 'vuex';
import { debounce } from 'lodash'; import { debounce } from 'lodash';
@ -167,6 +167,8 @@ import {
import { createComment } from '@/api/post'; import { createComment } from '@/api/post';
import { getSuggestUsers } from '@/api/user'; import { getSuggestUsers } from '@/api/user';
import { parsePostTag } from '@/utils/content'; import { parsePostTag } from '@/utils/content';
import type { MentionOption, UploadFileInfo, UploadInst } from 'naive-ui';
import { FileInfo } from 'naive-ui/lib/upload/src/interface';
const emit = defineEmits(['post-success']); const emit = defineEmits(['post-success']);
const props = defineProps({ const props = defineProps({
@ -182,15 +184,15 @@ const props = defineProps({
const store = useStore(); const store = useStore();
const optionsRef = ref([]); const optionsRef = ref<MentionOption[]>([]);
const showBtn = ref(false); const showBtn = ref(false);
const loading = ref(false); const loading = ref(false);
const submitting = ref(false); const submitting = ref(false);
const content = ref(''); const content = ref('');
const uploadRef = ref(null); const uploadRef = ref<UploadInst>();
const uploadType = ref('public/image'); const uploadType = ref('public/image');
const fileQueue = ref([]); const fileQueue = ref<UploadFileInfo[]>([]);
const imageContents = ref([]); const imageContents = ref<Item.CommentItemProps[]>([]);
const uploadGateway = import.meta.env.VITE_HOST + '/attachment'; const uploadGateway = import.meta.env.VITE_HOST + '/attachment';
const uploadToken = ref(); const uploadToken = ref();
@ -201,7 +203,7 @@ const loadSuggestionUsers = debounce((k) => {
k, k,
}) })
.then((res) => { .then((res) => {
let options = []; let options: MentionOption[] = [];
res.map((i) => { res.map((i) => {
options.push({ options.push({
label: i, label: i,
@ -216,7 +218,7 @@ const loadSuggestionUsers = debounce((k) => {
}); });
}, 200); }, 200);
const handleSearch = (k, prefix) => { const handleSearch = (k: string, prefix: string) => {
if (loading.value) { if (loading.value) {
return; return;
} }
@ -225,38 +227,38 @@ const handleSearch = (k, prefix) => {
loadSuggestionUsers(k); loadSuggestionUsers(k);
} }
}; };
const changeContent = (v) => { const changeContent = (v: string) => {
if (v.length > 200) { if (v.length > 200) {
return; return;
} }
content.value = v; content.value = v;
}; };
const setUploadType = (type) => { const setUploadType = (type: string) => {
uploadType.value = type; uploadType.value = type;
}; };
const updateUpload = (list) => { const updateUpload = (list: UploadFileInfo[]) => {
fileQueue.value = list; fileQueue.value = list;
}; };
const beforeUpload = async (data) => { const beforeUpload = async (data: any) => {
// 图片类型校验 // 图片类型校验
if ( if (
uploadType.value === 'public/image' && uploadType.value === 'public/image' &&
!['image/png', 'image/jpg', 'image/jpeg', 'image/gif'].includes( !['image/png', 'image/jpg', 'image/jpeg', 'image/gif'].includes(
data.file.file?.type (data.file as any).file?.type
) )
) { ) {
window.$message.warning(' png/jpg/gif '); window.$message.warning(' png/jpg/gif ');
return false; return false;
} }
if (uploadType.value === 'image' && data.file.file?.size > 10485760) { if (uploadType.value === 'image' && (data.file as any).file?.size > 10485760) {
window.$message.warning('10MB'); window.$message.warning('10MB');
return false; return false;
} }
return true; return true;
}; };
const finishUpload = ({ file, event }) => { const finishUpload = ({ file, event }: any): any => {
try { try {
let data = JSON.parse(event.target?.response); let data = JSON.parse(event.target?.response);
@ -272,14 +274,14 @@ const finishUpload = ({ file, event }) => {
window.$message.error(''); window.$message.error('');
} }
}; };
const failUpload = ({ file, event }) => { const failUpload = ({ file, event }: any): any => {
try { try {
let data = JSON.parse(event.target?.response); let data = JSON.parse(event.target?.response);
if (data.code !== 0) { if (data.code !== 0) {
let errMsg = data.msg || ''; let errMsg = data.msg || '';
if (data.details && data.details.length > 0) { if (data.details && data.details.length > 0) {
data.details.map((detail) => { data.details.map((detail: string) => {
errMsg += ':' + detail; errMsg += ':' + detail;
}); });
} }
@ -289,7 +291,7 @@ const failUpload = ({ file, event }) => {
window.$message.error(''); window.$message.error('');
} }
}; };
const removeUpload = ({ file }) => { const removeUpload = ({ file }: any) => {
let idx = imageContents.value.findIndex((item) => item.id === file.id); let idx = imageContents.value.findIndex((item) => item.id === file.id);
if (idx > -1) { if (idx > -1) {
imageContents.value.splice(idx, 1); imageContents.value.splice(idx, 1);
@ -353,7 +355,7 @@ const submitPost = () => {
submitting.value = false; submitting.value = false;
}); });
}; };
const triggerAuth = (key) => { const triggerAuth = (key: string) => {
store.commit('triggerAuth', true); store.commit('triggerAuth', true);
store.commit('triggerAuthKey', key); store.commit('triggerAuthKey', key);
}; };

@ -38,9 +38,10 @@
</div> </div>
</template> </template>
<script setup> <script setup lang="ts">
import { ref } from 'vue'; import { ref } from 'vue';
import { createCommentReply } from '@/api/post'; import { createCommentReply } from '@/api/post';
import { InputInst } from 'naive-ui';
const props = defineProps({ const props = defineProps({
commentId: { commentId: {
@ -57,11 +58,11 @@ const props = defineProps({
}, },
}); });
const emit = defineEmits(['reload', 'reset']); const emit = defineEmits(['reload', 'reset']);
const inputInstRef = ref(null); const inputInstRef = ref<InputInst>();
const showReply = ref(false); const showReply = ref(false);
const replyContent = ref(''); const replyContent = ref('');
const submitting = ref(false); const submitting = ref(false);
const switchReply = (status) => { const switchReply = (status: boolean) => {
showReply.value = status; showReply.value = status;
if (status) { if (status) {

@ -231,7 +231,7 @@
</template> </template>
<script setup> <script setup lang="ts">
import { ref, onMounted } from 'vue'; import { ref, onMounted } from 'vue';
import { useStore } from 'vuex'; import { useStore } from 'vuex';
import { debounce } from 'lodash'; import { debounce } from 'lodash';
@ -245,24 +245,27 @@ import {
} from '@vicons/ionicons5'; } from '@vicons/ionicons5';
import { createPost } from '@/api/post'; import { createPost } from '@/api/post';
import { parsePostTag } from '@/utils/content'; import { parsePostTag } from '@/utils/content';
import type { MentionOption, UploadFileInfo, UploadInst } from 'naive-ui';
const emit = defineEmits(['post-success']); const emit = defineEmits<{
(e: 'post-success', post: AnyObject): void
}>();
const store = useStore(); const store = useStore();
const optionsRef = ref([]); const optionsRef = ref<MentionOption[]>([]);
const loading = ref(false); const loading = ref(false);
const submitting = ref(false); const submitting = ref(false);
const showLinkSet = ref(false); const showLinkSet = ref(false);
const content = ref(''); const content = ref('');
const links = ref([]); const links = ref([]);
const uploadRef = ref(null); const uploadRef = ref<UploadInst>();
const attachmentPrice = ref(0); const attachmentPrice = ref(0);
const uploadType = ref('public/image'); const uploadType = ref('public/image');
const fileQueue = ref([]); const fileQueue = ref<UploadFileInfo[]>([]);
const imageContents = ref([]); const imageContents = ref<Item.CommentItemProps[]>([]);
const videoContents = ref([]); const videoContents = ref<Item.CommentItemProps[]>([]);
const attachmentContents = ref([]); const attachmentContents = ref<Item.CommentItemProps[]>([]);
const uploadGateway = import.meta.env.VITE_HOST + '/attachment'; const uploadGateway = import.meta.env.VITE_HOST + '/attachment';
const uploadToken = ref(); const uploadToken = ref();
@ -280,7 +283,7 @@ const loadSuggestionUsers = debounce((k) => {
k, k,
}) })
.then((res) => { .then((res) => {
let options = []; let options: MentionOption[] = [];
res.map((i) => { res.map((i) => {
options.push({ options.push({
label: i, label: i,
@ -301,7 +304,7 @@ const loadSuggestionTags = debounce((k) => {
k, k,
}) })
.then((res) => { .then((res) => {
let options = []; let options: MentionOption[] = [];
res.map((i) => { res.map((i) => {
options.push({ options.push({
label: i, label: i,
@ -316,7 +319,7 @@ const loadSuggestionTags = debounce((k) => {
}); });
}, 200); }, 200);
const handleSearch = (k, prefix) => { const handleSearch = (k: string, prefix: string) => {
if (loading.value) { if (loading.value) {
return; return;
} }
@ -327,20 +330,20 @@ const handleSearch = (k, prefix) => {
loadSuggestionTags(k); loadSuggestionTags(k);
} }
}; };
const changeContent = (v) => { const changeContent = (v: string) => {
if (v.length > 200) { if (v.length > 200) {
return; return;
} }
content.value = v; content.value = v;
}; };
const setUploadType = (type) => { const setUploadType = (type: string) => {
uploadType.value = type; uploadType.value = type;
}; };
const updateUpload = (list) => { const updateUpload = (list: UploadFileInfo[]) => {
fileQueue.value = list; fileQueue.value = list;
}; };
const beforeUpload = async (data) => { const beforeUpload = async (data: any) => {
// 图片类型校验 // 图片类型校验
if ( if (
uploadType.value === 'public/image' && uploadType.value === 'public/image' &&
@ -390,7 +393,7 @@ const beforeUpload = async (data) => {
return true; return true;
}; };
const finishUpload = ({ file, event }) => { const finishUpload = ({ file, event }: any): any => {
try { try {
let data = JSON.parse(event.target?.response); let data = JSON.parse(event.target?.response);
@ -418,14 +421,14 @@ const finishUpload = ({ file, event }) => {
window.$message.error(''); window.$message.error('');
} }
}; };
const failUpload = ({ file, event }) => { const failUpload = ({ file, event }: any): any => {
try { try {
let data = JSON.parse(event.target?.response); let data = JSON.parse(event.target?.response);
if (data.code !== 0) { if (data.code !== 0) {
let errMsg = data.msg || ''; let errMsg = data.msg || '';
if (data.details && data.details.length > 0) { if (data.details && data.details.length > 0) {
data.details.map((detail) => { data.details.map((detail: string) => {
errMsg += ':' + detail; errMsg += ':' + detail;
}); });
} }
@ -435,7 +438,7 @@ const failUpload = ({ file, event }) => {
window.$message.error(''); window.$message.error('');
} }
}; };
const removeUpload = ({ file }) => { const removeUpload = ({ file }: any) => {
let idx = imageContents.value.findIndex((item) => item.id === file.id); let idx = imageContents.value.findIndex((item) => item.id === file.id);
if (idx > -1) { if (idx > -1) {
imageContents.value.splice(idx, 1); imageContents.value.splice(idx, 1);
@ -530,7 +533,7 @@ const submitPost = () => {
submitting.value = false; submitting.value = false;
}); });
}; };
const triggerAuth = (key) => { const triggerAuth = (key: string) => {
store.commit('triggerAuth', true); store.commit('triggerAuth', true);
store.commit('triggerAuthKey', key); store.commit('triggerAuthKey', key);
}; };

@ -32,7 +32,7 @@
</n-card> </n-card>
</template> </template>
<script setup> <script setup lang="ts">
import { onMounted } from 'vue'; import { onMounted } from 'vue';
import { useStore } from 'vuex'; import { useStore } from 'vuex';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
@ -52,7 +52,7 @@ const props = defineProps({
default: false, default: false,
}, },
}); });
const switchTheme = (theme) => { const switchTheme = (theme: boolean) => {
if (theme) { if (theme) {
localStorage.setItem('PAOPAO_THEME', 'dark'); localStorage.setItem('PAOPAO_THEME', 'dark');
store.commit('triggerTheme', 'dark'); store.commit('triggerTheme', 'dark');
@ -73,7 +73,7 @@ const goBack = () => {
onMounted(() => { onMounted(() => {
if (!localStorage.getItem('PAOPAO_THEME')) { if (!localStorage.getItem('PAOPAO_THEME')) {
switchTheme(useOsTheme() === 'dark'); switchTheme((useOsTheme() as unknown as string) === 'dark');
} }
}); });
</script> </script>

@ -65,7 +65,7 @@
</div> </div>
</template> </template>
<script setup> <script setup lang="ts">
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
import { ShareOutline } from '@vicons/ionicons5'; import { ShareOutline } from '@vicons/ionicons5';
import { readMessage } from '@/api/user'; import { readMessage } from '@/api/user';
@ -75,13 +75,10 @@ const defaultavatar =
'https://assets.paopao.info/public/avatar/default/admin.png'; 'https://assets.paopao.info/public/avatar/default/admin.png';
const router = useRouter(); const router = useRouter();
const props = defineProps({ const props = withDefaults(defineProps<{
message: { message: Item.MessageProps
type: Object, }>(), {});
default: () => {}, const viewDetail = (message: Item.MessageProps) => {
},
});
const viewDetail = (message) => {
handleReadMessage(message); handleReadMessage(message);
if (message.type === 1 || message.type === 2 || message.type === 3) { if (message.type === 1 || message.type === 2 || message.type === 3) {
if (message.post && message.post.id > 0) { if (message.post && message.post.id > 0) {
@ -96,7 +93,7 @@ const viewDetail = (message) => {
} }
} }
}; };
const handleReadMessage = (message) => { const handleReadMessage = (message: Item.MessageProps) => {
if (message.is_read === 0) { if (message.is_read === 0) {
readMessage({ readMessage({
id: message.id, id: message.id,
@ -105,7 +102,7 @@ const handleReadMessage = (message) => {
message.is_read = 1; message.is_read = 1;
}) })
.catch((err) => { .catch((err) => {
console.log(res); console.log(err);
}); });
} }
}; };

@ -3,9 +3,18 @@ import router from './router'
import store from './store' import store from './store'
import App from './App.vue' import App from './App.vue'
import type { MessageApiInjection } from 'naive-ui/lib/message/src/MessageProvider'
// 通用字体 // 通用字体
import 'vfonts/Lato.css' import 'vfonts/Lato.css'
// 等宽字体 // 等宽字体
import 'vfonts/FiraCode.css' import 'vfonts/FiraCode.css'
createApp(App).use(router).use(store).mount('#app') createApp(App).use(router).use(store).mount('#app')
declare global {
interface Window {
$message: MessageApiInjection,
$store: any
}
}

@ -0,0 +1,18 @@
declare module '*.vue' {
import { DefineComponent } from 'vue'
const component: DefineComponent<{}, {}, any>
export default component
}
declare module '*.svg'
declare module '*.png'
declare module '*.jpg'
declare module '*.jpeg'
declare module '*.gif'
declare module '*.bmp'
declare module '*.tiff'
declare module '*.json'
interface AnyObject {
[key: string]: any
}

@ -9,7 +9,9 @@ export default createStore({
authModelShow: false, authModelShow: false,
authModelTab: 'signin', authModelTab: 'signin',
userInfo: { userInfo: {
id: 0,
username: '', username: '',
nickname: ''
}, },
}, },
mutations: { mutations: {

@ -0,0 +1,18 @@
declare module NetParams {
interface AuthUserLogin {
username?: string,
password?: string
}
interface UserGetCollections {
list: any[],
pager: AnyObject
}
interface PostGetPosts {
list: any[],
pager: AnyObject
}
}

@ -0,0 +1,20 @@
declare module NetReq {
interface AuthUserLogin {
token?: string
}
interface UserGetCollections {
list: any[],
pager: AnyObject
}
type UserGetSuggestUsers = string[]
type UserGetSuggestTags = string[]
interface PostGetPosts {
list: any[],
pager: AnyObject
}
}

@ -0,0 +1,45 @@
declare module Item {
interface UserInfo {
id: number,
username: string,
nickname: string,
avatar: string
}
interface CommentItemProps {
id: number | string,
content: string
}
interface CommentProps extends CommentItemProps {
type: number,
user: UserInfo,
contents: CommentProps[],
replies: ReplyProps[],
ip_loc: string,
created_on: number
}
interface ReplyProps {
id: number,
user_id: number,
user: UserInfo
}
interface PostProps {
id: number,
}
interface MessageProps {
id: number,
type: number,
is_read: number,
sender_user: UserInfo
post: PostProps,
post_id: number,
created_on: number,
breif: string
}
}

@ -1,7 +1,7 @@
export const parsePostTag = content => { export const parsePostTag = (content: string) => {
const tags = [] const tags: string[] = []
const users = [] const users: string[] = []
var tagExp = /(#|)([^#@])+?\s+?/g // 这⾥中⽂#和英⽂#都会识别 var tagExp = /(#|)([^#@])+?\s+?/g // 这⾥中⽂#和英⽂#都会识别
var atExp = /@([a-zA-Z0-9])+?\s+?/g // 这⾥中⽂#和英⽂#都会识别 var atExp = /@([a-zA-Z0-9])+?\s+?/g // 这⾥中⽂#和英⽂#都会识别
content = content content = content

@ -6,11 +6,11 @@ import moment from 'moment';
import 'moment/dist/locale/zh-cn'; import 'moment/dist/locale/zh-cn';
moment.locale('zh-cn'); moment.locale('zh-cn');
export const formatTime = time => { export const formatTime = (time: number) => {
return moment.unix(time).utc(true).format('YYYY/MM/DD HH:mm:ss'); return moment.unix(time).utc(true).format('YYYY/MM/DD HH:mm:ss');
}; };
export const formatRelativeTime = time => { export const formatRelativeTime = (time: number) => {
return moment.unix(time).fromNow(); return moment.unix(time).fromNow();
}; };

@ -9,7 +9,7 @@ service.interceptors.request.use(
config => { config => {
// 鉴权Header // 鉴权Header
if (localStorage.getItem('PAOPAO_TOKEN')) { if (localStorage.getItem('PAOPAO_TOKEN')) {
config.headers['Authorization'] = 'Bearer ' + localStorage.getItem('PAOPAO_TOKEN'); (config.headers as any)['Authorization'] = 'Bearer ' + localStorage.getItem('PAOPAO_TOKEN');
} }
return config; return config;

@ -1,9 +1,9 @@
// 滚动到顶部 // 滚动到顶部
export const scrollToTop = (scrollDuration) => { export const scrollToTop = (scrollDuration: number) => {
var cosParameter = window.scrollY / 2; var cosParameter = window.scrollY / 2;
var scrollCount = 0; var scrollCount = 0;
var oldTimestamp = performance.now(); var oldTimestamp = performance.now();
function step(newTimestamp) { function step(newTimestamp: number) {
scrollCount += scrollCount +=
Math.PI / (scrollDuration / (newTimestamp - oldTimestamp)); Math.PI / (scrollDuration / (newTimestamp - oldTimestamp));
if (scrollCount >= Math.PI) window.scrollTo(0, 0); if (scrollCount >= Math.PI) window.scrollTo(0, 0);

@ -16,7 +16,7 @@
</div> </div>
</template> </template>
<script setup> <script setup lang="ts">
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
const router = useRouter(); const router = useRouter();

@ -30,7 +30,7 @@
</div> </div>
</template> </template>
<script setup> <script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'; import { ref, onMounted, computed, watch } from 'vue';
import { useStore } from 'vuex'; import { useStore } from 'vuex';
import { useRoute, useRouter } from 'vue-router'; import { useRoute, useRouter } from 'vue-router';
@ -41,8 +41,8 @@ const route = useRoute();
const router = useRouter(); const router = useRouter();
const loading = ref(false); const loading = ref(false);
const list = ref([]); const list = ref<any[]>([]);
const page = ref(+route.query.p || 1); const page = ref(+(route.query.p as any) || 1);
const pageSize = ref(20); const pageSize = ref(20);
const totalPage = ref(0); const totalPage = ref(0);
@ -63,7 +63,7 @@ const loadPosts = () => {
loading.value = false; loading.value = false;
}); });
}; };
const updatePage = (p) => { const updatePage = (p: number) => {
page.value = p; page.value = p;
loadPosts(); loadPosts();
}; };

@ -34,7 +34,7 @@
</div> </div>
</template> </template>
<script setup> <script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'; import { ref, onMounted, computed, watch } from 'vue';
import { useStore } from 'vuex'; import { useStore } from 'vuex';
import { useRoute, useRouter } from 'vue-router'; import { useRoute, useRouter } from 'vue-router';
@ -45,8 +45,8 @@ const route = useRoute();
const router = useRouter(); const router = useRouter();
const loading = ref(false); const loading = ref(false);
const list = ref([]); const list = ref<any[]>([]);
const page = ref(+route.query.p || 1); const page = ref(+(route.query.p as string) || 1);
const pageSize = ref(20); const pageSize = ref(20);
const totalPage = ref(0); const totalPage = ref(0);
const title = computed(() => { const title = computed(() => {
@ -54,9 +54,9 @@ const title = computed(() => {
if (route.query && route.query.q) { if (route.query && route.query.q) {
if (route.query.t && route.query.t === 'tag') { if (route.query.t && route.query.t === 'tag') {
t = '#' + decodeURIComponent(route.query.q); t = '#' + decodeURIComponent(route.query.q as string);
} else { } else {
t = ': ' + decodeURIComponent(route.query.q); t = ': ' + decodeURIComponent(route.query.q as string);
} }
} }
@ -66,7 +66,7 @@ const title = computed(() => {
const loadPosts = () => { const loadPosts = () => {
loading.value = true; loading.value = true;
getPosts({ getPosts({
query: route.query.q ? decodeURIComponent(route.query.q) : null, query: route.query.q ? decodeURIComponent(route.query.q as string) : null,
type: route.query.t, type: route.query.t,
page: page.value, page: page.value,
page_size: pageSize.value, page_size: pageSize.value,
@ -83,7 +83,7 @@ const loadPosts = () => {
}); });
}; };
const onPostSuccess = (post) => { const onPostSuccess = (post: Item.PostProps) => {
router.push({ router.push({
name: 'post', name: 'post',
query: { query: {
@ -92,7 +92,7 @@ const onPostSuccess = (post) => {
}); });
}; };
const updatePage = (p) => { const updatePage = (p: number) => {
router.push({ router.push({
name: 'home', name: 'home',
query: { query: {
@ -113,14 +113,14 @@ watch(
}), }),
(to, from) => { (to, from) => {
if (to.refresh !== from.refresh) { if (to.refresh !== from.refresh) {
page.value = +route.query.p || 1; page.value = +(route.query.p as string) || 1;
setTimeout(() => { setTimeout(() => {
loadPosts(); loadPosts();
}, 0); }, 0);
return; return;
} }
if (from.path !== '/post' && to.path === '/') { if (from.path !== '/post' && to.path === '/') {
page.value = +route.query.p || 1; page.value = +(route.query.p as string) || 1;
setTimeout(() => { setTimeout(() => {
loadPosts(); loadPosts();

@ -0,0 +1,3 @@
/// <reference types="vite/client" />
/// <reference types="vue/ref-macros" />
/// <reference types="naive-ui/volar" />

@ -0,0 +1,14 @@
import { ComponentCustomProperties } from 'vue'
import { Store } from 'vuex'
declare module '@vue/runtime-core' {
// 声明自己的 store state
interface State {
[key: string]: any
}
// 为 `this.$store` 提供类型声明
interface ComponentCustomProperties {
$store: Store<State>
}
}

@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"moduleResolution": "node",
"strict": true,
"jsx": "preserve",
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"lib": ["esnext", "dom"],
"types": [
"node"
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}

File diff suppressed because it is too large Load Diff
Loading…
Cancel
Save