1. 程式人生 > >vue--動態路由和get傳值

vue--動態路由和get傳值

log port new console 組件 edi com header news

動態路由:

<template>
  <div id="News">
    <v-header></v-header>
    <hr>
    {{title}}
    <br>
    <p v-for="(x,k) in list">
      <!-- <router-link to="/content/123">{{k}}-{{x}}</router-link> -->
      <!-- 因為要綁定我們的動態數據 所以要用 : 然後做拼接 -->
      <
router-link :to="‘/content/‘+k">{{k}}-{{x}}</router-link> </p> </div> </template> <script> import Header from ./Header.vue; export default { name: News, data () { return { title:我是新聞News組件, list:[111,222,3330,444] } }, methods:{}, components:{
v-header:Header, } } </script>

點擊之後能夠跳轉到一個詳情:可以新建一個詳情的組件:

<template>
    <div id="content">
        {{title}}----{{aid}}        
    </div>
</template>
<script>
export default {
  name: Header,
  data () {
    return {
      title:我是一個詳情頁面,
      aid:‘‘,
    }
  },
  methods:{
    run(){},
  },
  mounted(){
      
// 獲取傳遞過來的動態路由的值 console.log(this.$route.params); console.log(this.$route.params[aid]); this.aid = this.$route.params[aid]; } } </script> </script>

此時還需要配置路由:

// 1、創建組件
import Header from ‘./components/Header.vue‘
import Home from ‘./components/Home.vue‘
import News from ‘./components/News.vue‘
import Content from ‘./components/Content.vue‘

// 2、配置路由
const routes = [
  { path: ‘/home‘, component: Home },
  { path: ‘/news‘, component: News },
  { path: ‘/content‘, component: Content },
  { path: ‘/content/:aid‘, component: Content },
  { path: ‘*‘, redirect:‘/home‘}, // 默認跳轉路由
]

get傳值:

<p v-for="(x,k) in list">
  <!-- <router-link to="/content?aid=123">{{k}}-{{x}}</router-link> -->
  <router-link :to="‘/content?aid=‘+k">{{k}}-{{x}}</router-link>
</p>

配置路由:

// 2、配置路由
const routes = [
  { path: ‘/home‘, component: Home },
  { path: ‘/news‘, component: News },
  { path: ‘/content‘, component: Content },
  { path: ‘*‘, redirect:‘/home‘}, // 默認跳轉路由
]

獲取參數:

mounted(){
    // 獲取get傳遞過來的動態路由的值
    console.log(this.$route.query);
    console.log(this.$route.query[‘aid‘]);
    this.aid = this.$route.query[‘aid‘];
}

vue--動態路由和get傳值