视图使用: 1): <router-link :to="{name: 'main'}">主页</router-link> 2): this.$router.push({ name:'course-detail', });
router.js
routes: [ // ... { path: '/course/:id/detail', name: 'course-detail', component: CourseDetail }, ]注意:// path如果是通过to直接访问,路由必须完全对应// :id代表可以完成任意内容匹配,用变量id保存
跳转.vue
<template> <!-- 1.标签跳转 --> <router-link :to="`/course/${course.id}/detail`">{{ course.name }}</router-link> </template> <script> // ... goDetail() { // 2.逻辑跳转 this.$router.push(`/course/${this.course.id}/detail`); } </script>
接收.vue
created() { let id = this.$route.params.id; }router.js
routes: [ // ... { path: '/course/detail', name: 'course-detail', component: CourseDetail }, ]
跳转.vue
<template> <!-- 1.标签跳转 --> <router-link :to="{ name: 'course-detail', query: {id: course.id} }">{{ course.name }}</router-link> </template> <script> // ... goDetail() { // 2.逻辑跳转 this.$router.push({ name: 'course-detail', query: { id: this.course.id } }); } </script>
接收.vue
created() { let id = this.$route.query.id; }
store.js
export default new Vuex.Store({ state: { cTitle:'课程页', hTitle:'主页' }, mutations: {}, actions: {} })
SetTitle.vue
<template> <div> <Nav></Nav> <p> 修改课程页标题 <input type="text" v-model="cTitle"> <button @click="changeCTitle">修改</button> </p> <p> 修改主页标题 <input type="text" v-model="hTitle"> <button @click="changeHTitle">修改</button> </p> </div> </template> <script> import Nav from '@/components/Nav' export default { name: "SetTitle", components: { Nav }, data() { return { cTitle: '', hTitle: '', } }, methods: { changeCTitle() { this.$store.state.cTitle = this.cTitle; // this.$store.state.cTitle 就可以拿到vuex仓库中state内的值 // store是vue实例的成员 // this.$store.commit('setCTitle', this.cTitle); }, changeHTitle(){ this.hTitle && (localStorage.hTitle = this.hTitle); } } } </script> <style scoped> </style>在任意组件中给仓库变量赋值
this.$store.state.title = 'newTitle' this.$store.commit('setTitle', 'newTitle')在任意组件中取仓库变量的值
console.log(this.$store.state.title)