初识vue 2.0(9):vue-router数据传递
1. 在main.js 中引入
import router from './router' new Vue({ el: '#app', router,//我在这儿 template: '<App/>', components: { App } })
2. 在/router/index.js中定义命名路由
import Vue from 'vue' import Router from 'vue-router' import Hello from '@/components/Hello' import Game from '@/components/Game' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'Hello', component: Hello }, { path: '/game', name: 'Game', component: Game } ] })
3. 在app.vue中引入路由视图
<template> <div id="app"> <router-view></router-view> </div> </template>
4. 在Hello.vue组件中定义类似GET路由请求
<template> <div class="hello"> <h2>{{ msg }}</h2> <router-link to="Game">Game</router-link> <router-link :to="{path:'Game',query:{id:id,msg:msg}}">Game</router-link> <a href="javascript:;" @click="jump">Game</a> </div> </template> <script> export default { name: 'hello', data () { return { msg:"Hello", id:123, } }, methods: { jump(){ //类GET this.$router.push({ path:'Game', query:{id:this.id,msg:this.msg} }) } }, created() { console.log(this.$route.params); } } </script> <style> .hello{ background-color:#E1FFFF; } </style>
5. 在Game.vue组件中定义类似POST路由请求
<template> <div class="game"> <h2>{{ msg }}</h2> <router-link :to="{name:'Hello',params:{id:id,msg:msg}}">Hello</router-link> <a href="javascript:;" @click="jump">Hello</a> </div> </template> <script> export default { name: 'game', data () { return { msg: 'Game', id:321, } }, methods: { jump(){ //类GET this.$router.push({ name:'Hello', params:{id:this.id,msg:this.msg} }) } }, created() { console.log(this.$route.query); } } </script> <style lang="css"> .game{ border: 1px solid #00FF00; width: 200px; } </style>
因为使用了命名路由,要注意路由请求中的name或path
参考:https://router.vuejs.org/