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>
<script>
var testLogin = Vue.component("login",{
template:`
<div>
<h1>商品清單</h1>
<table>
<thead>
<tr>
<th></th>
<th>書籍名稱</th>
<th>價格</th>
<th>購買數量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for = "(item,index) in book">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>
<button @click = "btn(index)" v-bind:disabled = "item.count <= 1">-</button>
{{item.count}}
<button @click = "btns(index)">+</button>
</td>
<td>
<router-link :to="{path:'myRegister',query: { id: item.id,name:item.name,price:item.price,count:item.count }}">加入購物車</router-link>
</td>
</tr>
</tbody>
<h2>總價格 {{totalprice}}</h2>
</table>
</div>
`,
data:function(){
return {
book:[
{
id :1,
name:'《Java從入門到精通》',
price:85+".00",
count:1
},
{
id :2,
name:'《C語言從入門到精通》',
price:59+".00",
count:1
},
{
id :3,
name:'《C++從入門到精通》',
price:39+".00",
count:1
},
{
id :4,
name:'《PHP從入門到精通》',
price:128+".00",
count:1
}
],
}
},
methods:{
btn(index){
this.book[index].count--;
},
btns(index){
this.book[index].count++
},
},
computed:{
totalprice:function(){
let result = 0
for(let i =0;i<this.book.length;i++){
result += this.book[i].price * this.book[i].count
}
return result+".00"
}
}
/*to後面是路由位址*/
})
var testRegister = Vue.component("register",{
methods:{
jumpToLogin:function(){
this.$router.push('/myLogin');
}
},
template:`
<div>
<h1>商品詳情</h1>
<table>
<thead>
<tr>
<th></th>
<th>書籍名稱</th>
<th>價格</th>
<th>購買數量</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{this.$route.query.id}}</td>
<td>{{this.$route.query.name}}</td>
<td>{{this.$route.query.price}}</td>
<td>
{{this.$route.query.count}}
</td>
</tr>
</tbody>
<h2>總價格 {{totalprice}}</h2>
</table>
<button @click="jumpToLogin">傳回</button>
</div>
`,
computed:{
totalprice:function(){
var result = 0;
result += this.$route.query.price * this.$route.query.count;
return result+".00"
}
}
})
//配置路由詞典
const myRoutes =[
{path:'',component:testLogin},
{path:'/myLogin',component:testLogin},
{path:'/myRegister',component:testRegister}
]
const myRouter = new VueRouter({
routes:myRoutes
})
new Vue({
router:myRouter,
el:"#container",
data:{
}
})
</script>
</body>
</html>