Vue中路由中文传参

前言

Vue路由传参的时候如果是中文会乱码

前端

编码使用encodeURIComponent,解码使用decodeURIComponent

编码

传参

1
2
3
4
5
6
7
router.push({
path: '/report_subject',
query: {
subjectid: '1NJCIN',
subjectname: encodeURIComponent('语文'),
}
})

解码

获取

1
2
3
4
5
6
7
import { useRoute } from 'vue-router'
// 使用 useRoute 函数获取当前路由信息
const route = useRoute()

onMounted(() => {
console.log('examname', decodeURIComponent(route.query.examname as string))
})

或者直接用JS获取

1
2
3
4
5
6
7
8
9
10
11
12
export function getRequestParas() {
const url = location.href
const paras = {}
if (url.indexOf('?') !== -1) {
const str = url.substr(url.indexOf('?') + 1)
const strs = str.split('&')
for (let i = 0; i < strs.length; i++) {
paras[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1])
}
}
return paras
}

获取

1
2
3
4
5
6
7
8
9
10
11
onMounted(() => {
const paras = getRequestParas() as {
examname: string
typename: string
datestr: string
}
const { examname, typename, datestr } = paras
pageData.value.examname = decodeURIComponent(examname)
pageData.value.typename = decodeURIComponent(typename)
pageData.value.datestr = decodeURIComponent(datestr)
})

Java

Java必须编码两次

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class Main {
public static void main(String[] args) {
String baseStr = "http://localhost:8888/#/report_cover";
String url = baseStr + "?examname=" + encodeUrl(encodeUrl("九年级第二次月考学情调研")) + "&typename=" + encodeUrl("学科素养报告") + "&datestr=" + encodeUrl("2025年05月13日");
System.out.println(url);
}

public static String encodeUrl(String str) {
return URLEncoder.encode(str, StandardCharsets.UTF_8);
}
}