Phe*_*nix 4 vue.js vuejs2 vuejs3
我目前正在学习 VUEJS,对此完全陌生。所以我需要帮助。我想从 URL 中获取 ID,例如:
网址:
abc.net/dashboard/a/123456789
Run Code Online (Sandbox Code Playgroud)
我想要123456789文本格式的。
cod*_*ine 10
如果您使用vue-routeroptions api,这可以指导您
import Vue from 'vue';
import VueRouter from 'vue-router';
import DashboardComponent from "./path/DashboardComponent";
Vue.use(VueRouter);
export default new VueRouter({
routes: [
{ path: '/dashboard/a/:id', component: DashboardComponent }//where :id is the dynamic id you wish to access from the browser
]
})
Run Code Online (Sandbox Code Playgroud)
在你的DashboardComponent
<template>
<div>
{{id}} //this will show the id in plain text
</div>
</template>
<script>
export default {
name: 'Dashboard',
data(){
return {
id: this.$route.params.id //this is the id from the browser
}
},
}
</script>
Run Code Online (Sandbox Code Playgroud)
对于带有 compositio API 的 Vue 3
<script setup>
import { defineProps, onMounted } from "vue";
import { useRouter } from "vue-router";
const props = defineProps( {
id: {
type: Number,
required: true,
}
onMounted( () => {
console.log(props.id)
} )
</script>
Run Code Online (Sandbox Code Playgroud)
在您的router.js文件中,
import { createWebHistory, createRouter, } from 'vue-router'
const routes = [
{
name: "Dashboard",
path: "/dashboard/a/:id",
component: () => import('./components/../file.vue'),
props: true
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
Run Code Online (Sandbox Code Playgroud)
这可以通过简单的 javascript 轻松完成
const url = window.location.href;
const lastParam = url.split("/").slice(-1)[0];
console.log(lastParam);
Run Code Online (Sandbox Code Playgroud)
如果您使用vue-router并且您加载的页面在router.js中定义。然后简单的调用this.$route.params