</div>
</template>
<script>
import router from '../router'
export default {
name: 'Page2',
data () {
return {
id: 0,
msg: 'Hey Nic Raboy'
}
},
created() {
this.id = this.$route.params.id;
},
methods: {
navigate() {
router.go(-1);
}
}
}
</script>
<style scoped>
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
与之前的例子相比,我们在上面的组件增加了一些内容
首先,您将注意到我们正在data方法中初始化一个id值。这是为了防止出现任何未定义的错误
每次创建组件时,Vue 都会调用其生命周期钩子的 Created 方法。在Created方法中,我们从$route获得传递的id值,并将其设置为局部变量。这个本地id变量在<template>块中
但是,如果我们需求传递更复杂的参数或者是可选参数,这时候就该换一种方式了
利用 Query 参数传递数据
Vue 中的查询参数与路由器参数的工作原理类似,但它们不是必需的,而且你并不需要事先修改路由
回到之前的src/components/page1.vue 文件上,其中 <template> 块如下:
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<router-link :to="{ name: 'Page2', params: { id: 1234 }, query: { debug: true }}">Navigate to Page2</router-link>
</div>
</template>
注意,这一次我们将传递URL或路由器参数以及一组新的Query参数。这些Query参数可以是任意数量的键值对
我们来看一下在接受端怎么处理这些 Query 参数
打开src/components/page2.vue 文件, 修改<script> 如下:
<script>
import router from '../router' export default {
name: 'Page2',
data () {
return {
debug: false,
id: 0,
msg: 'Hey Nic Raboy'
}
},
created() {
this.id = this.$route.params.id;
if(this.$route.query.debug) {
this.debug = this.$route.query.debug;
}
},
methods: {
navigate() {
router.go(-1);
}
}
}
</script>
就像使用路由器参数一样,我们在 data 方法中初始化了一个占位符变量。在Created方法中,我们检查Query参数中是否存在 debug 参数,如果存在,将其设置为本地变量










