攜帶query參數(shù)
-
傳遞參數(shù)
【方式一:通過查詢字符串直接拼接在路徑后面】
【方式二:傳遞一個(gè)對象,路徑是path屬性,拼接的參數(shù)是query屬性,推薦】<template> <div> <ul> <li v-for="item in dataList" :key="item.id"> <!-- 方式一:模板字符串拼接 --> <router-link :to="`/list/detail?id=${item.id}&title=${item.title}&content=${item.content}`">進(jìn)入{{item.title}},查看詳情</router-link> <!-- 方式二:對象寫法 --> <router-link :to="{ path: '/list/detail', query: { id: item.id, title: item.title, content: item.content } }">進(jìn)入{{item.title}},查看詳情</router-link> </li> </ul> <router-view></router-view> </div> </template> <script> name: 'List', data() { return { dataList: [{ id: 1, title: '標(biāo)題1', content: '內(nèi)容1' }, { id: 2, title: '標(biāo)題2', content: '內(nèi)容2' }, { id: 3, title: '標(biāo)題3', content: '內(nèi)容3' }] } } </script>
-
接收參數(shù)
【直接在$route.query中獲取】<template> <div> <p>id:{{$route.query.id}}</p> <p>標(biāo)題:{{$route.query.title}}</p> <p>內(nèi)容:{{$route.query.content}}</p> </div> </template> <script> export default { name: 'Detail' } </script>
攜帶params參數(shù)
-
router/index.js
【需要在router中配置path、name】import Vue from 'vue'; import VueRouter from 'vue-router'; Vue.use(VueRouter); export default new VueRouter({ routes: [{ name: 'xiangqing', path: '/detail/:id/:title/:content', // 需要通過這種方式給參數(shù)占個(gè)坑 component: 'Detail' }] });
-
傳遞參數(shù)
<template> <div> <router-link to="/detail/001/標(biāo)題/內(nèi)容">進(jìn)入詳情</router-link> <!-- 字符串方式 --> <router-link :to="{ name: 'xiangqing', params: { id: '001', title: '標(biāo)題', content: '內(nèi)容' } }">進(jìn)入詳情</router-link> <!-- 使用對象方式時(shí),只能使用name屬性,不能使用path --> </div> </template>
-
接收參數(shù)
<template> <div> <p>id: {{$route.params.id}}</p> <p>標(biāo)題:{{$route.params.title}}</p> <p>內(nèi)容:{{$route.params.content}}</p> </div> </template>
上述接收參數(shù)的方式存在代碼冗余,利用props方式接收query、params參數(shù),簡化代碼
-
在router/index.js中配置props屬性文章來源:http://www.zghlxwxcb.cn/news/detail-642531.html
import Vue from 'vue'; import VueRouter from 'vue-router'; import List from '@/pages/List'; import Detail from '@/pages/Detail' Vue.use(VueRouter); export default new VueRouter({ routes: [{ path: '/list', component: List, children: [{ path: 'detail', component: Detail, props: true, // props設(shè)置為true,在組件中只能接收params方式傳過來的參數(shù),query參數(shù)無法獲取 props($route) { // props為函數(shù),功能強(qiáng)大,query、params參數(shù)都可以獲取 return { id: $route.query.id, title: $route.query.title, content: $route.query.content } // 或者 return { id: $route.params.id, title: $route.params.title, content: $route.params.content } } }] }] });
-
接收參數(shù)文章來源地址http://www.zghlxwxcb.cn/news/detail-642531.html
<template> <div> <p>id: {{id}}</p> <p>title: {{title}}</p> <p>content: {{content}}</p> </div> </template> <script> export default { name: 'Detail', props: ['id', 'title', 'content'] } </script>
到了這里,關(guān)于Vue Router攜帶并接收query、params參數(shù)方式的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!