安装
安装vue-cli 这是vue的脚手架
npm install vue-cli -g
创建项目
vue init webpack 项目名
下载依赖
npm install
运行
npm run dev
打包
npm run build
常用指令
[v-bind和v-on]
v-bind指令用于设置HTML属性:v-bind:href 缩写为 :href
<a :href="{{url}}">aa</a>
v-on 指令用于绑定HTML事件 :v-on:click 缩写为 @click
<a @click="get()">aa</a>
<a v-on:click="get()">aa</a>
<div id="three">
<input type="button" value="点我" @click="onClick"/>
</div>
var three = new Vue({
el: "#three",
methods: {
onClick:function () {
console.log("This is Test")
}
}
})
条件,循环
v-if &v-for
<template v-if="list.length">
</template>
<div v-else>空</div>
-----
<tr v-for="(item, index) in list">
<td>{{index+1}}</td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>
<el-button @click="handleReduce(index)" :disabled="item.count ===1">-</el-button>
{{item.count}}
<el-button @click="handleAdd(index)">+</el-button>
</td>
<td>
<el-button @click="handleRemove(index)">移除</el-button>
</td>
</tr>
表格Demo
表格CRUD
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Vue 购物车Demo</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<!-- <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> -->
<!-- 引入样式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<link rel="stylesheet" type="text/css" href="index.css"/>
<!-- 引入组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
</head>
<body>
<div id="app" v-cloak>
<template v-if="list.length">
<table>
<thead>
<tr>
<th>\</th>
<th>商品名称</th>
<th>商品单价</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in list">
<td>{{index+1}}</td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>
<el-button @click="handleReduce(index)" :disabled="item.count ===1">-</el-button>
{{item.count}}
<el-button @click="handleAdd(index)">+</el-button>
</td>
<td>
<el-button @click="handleRemove(index)">移除</el-button>
</td>
</tr>
</tbody>
</table>
<div>总价:¥{{totalPrice}}</div>
</template>
<div v-else>购物车为空</div>
</div>
<script src="index.js" type="text/javascript"></script>
</body>
</html>
css
table{
border: 1px solid #e9e9e9 ;
border-collapse: collapse ;
border-spacing: 0 ;
empty-cells: show ;
}
th, td{
padding: 8px 16px;
border: 1px solid #e9e9e9 ;
text-align: left ;
}
js
var app = new Vue({
el: '#app',
data: {
list:[{
id:1,
name:'iphone7',
price:6688,
count:5
},
{
id:2,
name:'iphonex',
price:18999,
count:2
},
{
id:3,
name:'iphone8',
price:13888,
count:3
}]
},
methods: {
handleReduce:function(index){
if(this.list[index].count===1) return ;
this.list[index].count-- ;
},
handleAdd:function(index){
this.list[index].count++ ;
},
handleRemove:function(index){
this.list.splice(index,1) ;
},
},
computed:{
totalPrice:function(){
var total = 0 ;
for(var i = 0; i<this.list.length ;i++){
var item = this.list[i] ;
total +=item.price * item.count ;
}
return total.toString().replace(/\B(?=(\d{3})+$)/g,',') ;
}
}
})
运行效果:
最后推荐一本书籍《Vue.js实战》,这本书籍配合官方文档入手会避免很多坑
网友评论