<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="./vue.js"></script>
<!-- 1. 先引入vue-router文件 -->
<script src="./vue-router.js"></script>
<script src="./axios.js"></script>
<style>
ul.myul {
display: flex;
}
li.navitem {
list-style-type: none;
padding: 0 20px;
}
.product {
border: 1px solid blueviolet;
}
.index {
border: 1px solid pink;
}
.cookbook {
border: 1px solid black;
}
</style>
</head>
<body>
<div id="app">
<ul class="myul">
<li class="navitem"><router-link to="/home">首页</router-link></li>
<li class="navitem"><router-link to="/product/11">蔬菜</router-link></li>
<li class="navitem"><router-link to="/product/22">水果</router-link></li>
<li class="navitem"><router-link to="/product/33">肉类</router-link></li>
</ul>
<router-view></router-view>
</div>
<script>
let myhome = Vue.component('home', {
template: '<div class="index">这是首页</div>'
})
let myproduct = Vue.component('product', {
template: `
<div class="product">
<p>这是商品分类,该分类的编号是{{$route.params.cid}}</p>
<ul>
<li v-for="(item, index) in products" :key="index">{{item}}</li>
</ul>
<button @click='viewbook'>查看菜谱</button>
<router-view></router-view>
</div>
`,
data () {
return {
products: []
}
},
methods: {
viewbook() {
// 跳转到菜谱对应的路由规则,注意这里是$router⭐,这就是编程式导航,就是js实现的路由跳转
this.$router.push({name: 'book'})
}
},
watch: {
'$route': {
handler(to, from) {
let cid = to.params.cid
console.log(cid);
axios.get(`http://192.168.75.84:3000/list/${cid}`)
.then(res => {
this.products = res.data.products
})
},
immediate: true
}
}
})
// 菜谱组件
let cookbook = Vue.component('book', {
template: '<div class="cookbook">青椒炒肉/土豆炖牛肉/清水白菜。。。。。</div>'
})
let router = new VueRouter({
routes: [
{name: 'index', path: '/home', component: myhome},
// 1. 定义子路由通过children属性设置,children属性就是一个一个的对象,对象中也是name/path/component
{name: 'productCate', path: '/product/:cid', component: myproduct,
children: [
// 在子路由中,path属性不能加 /
{name: 'book', path: 'cook', component: cookbook}
]
},
// path: '*' 表示如果匹配不到上面的路由规则,那么剩下的所有路由规则都走下面这条规则(默认首页),redirect表示重定向
{name: 'default', path: '*', redirect: {name: 'index'}}
]
})
var vm = new Vue({
el: '#app',
router,
data: {
}
})
</script>
</body>
</html>
Vue路由嵌套
最新推荐文章于 2021-04-30 09:26:13 发布