When using Vue for development, it is often necessary to use the "routing parameters" function, but sometimes the parameters passed contain Chinese characters, and the problem of Chinese garbled characters will occur. This is because the browser's URL only accepts ASCII encoding and does not support Chinese character encoding, so garbled characters will appear when transmitting Chinese characters. This article will introduce how to solve this problem in Vue.
Solution
When passing Chinese characters to the route, you can use the encodeURIComponent() function in JavaScript. coding. The function of this function is to convert Chinese characters into URL encoding so that Chinese characters can be correctly transmitted in the URL.
Code example:
this.$router.push({ path: '/detail', query: { id: 1, title: encodeURIComponent('这是中文标题') } })
Note: Using this method requires decoding on the page that receives the parameters. The decoding method is the decodeURIComponent() function.
When using vue-router to pass parameters for routing, there are two ways to pass parameters, one is to use query, and the other is to use vue-router to pass parameters. is to use params. params is to add parameters to the routing address rather than as query parameters, which can avoid the problem of Chinese garbled characters.
Code example:
this.$router.push({ path: `/detail/${encodeURIComponent('这是中文标题')}`, params: { id: 1 } })
Note: At this time, you need to declare the dynamic routing of routing parameters.
If it is just an ordinary string instead of a routing parameter, you can also use Chinese characters directly in English notation or Unicode code to avoid the problem of Chinese garbled characters.
Code example:
console.log('这是一段中文字符') // 输出这是一段中文字符 console.log('\u8FD9\u662F\u4E00\u6BB5\u4E2D\u6587\u5B57\u7B26') // 输出这是一段中文字符
Summary
This article introduces the correct way to pass Chinese characters in Vue, using the encodeURIComponent() function encoding and using the params parameter of vue-router Directly using English notation or Unicode codes are both feasible methods, and you can choose to use them according to the actual situation.
The above is the detailed content of How to solve the Chinese garbled characters in vue routing parameters. For more information, please follow other related articles on the PHP Chinese website!