初学者学习Vue组件和路由代码片段:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>商品首页</title>
<link rel="stylesheet" href="css/shopXq.css">
<script src="js/vue.min.js" type="text/javascript" charset="utf-8"></script>
<script src="node_modules/vue-router/dist/vue-router.min.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="container">
<!--通过router-view指定盛放组件的容器 -->
<router-view></router-view>
</div>
<template id="productList">
<div>
<h1>商品列表</h1>
<ul v-for="(item,index) in book">
<li><router-link :to="{path:'productDetails',query: { id: item.id,name:item.name}}">{{item.name}}</router-link></li>
</ul>
</div>
</template>
<template id="productDetails">
<div>
<h1>商品详情</h1>
<ul>
<li>{{this.$route.query.id}}-{{this.$route.query.name}}</li>
</ul>
<button @click="jumpToList">返回</button>
</div>
</template>
<script>
var productList = {
template:'#productList',
data:function(){
return {
book:[
{
id :1,
name:'《Java从入门到精通》',
},
{
id :2,
name:'《C语言从入门到精通》',
},
{
id :3,
name:'《C++语言从入门到精通》',
},
{
id :4,
name:'《C++语言从入门到精通》',
}
],
}
},
/*to后面是路由地址*/
};
var productDetails = {
template:'#productDetails',
methods:{
jumpToList:function(){
this.$router.push('/productList');
}
},
};
//配置路由词典
const myRoutes =[
{path:'',component:productList},
{path:'/productList',component:productList},
{path:'/productDetails',component:productDetails}
]
const myRouter = new VueRouter({
routes:myRoutes
})
new Vue({
router:myRouter,
el:"#container",
data:{
}
})
</script>
</body>
</html>