<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#app {
width: 600px;
margin: 10px auto;
}
.tb {
border-collapse: collapse;
width: 100%;
}
.tb th {
background-color: #0094ff;
color: white;
}
.tb td,
.tb th {
padding: 5px;
border: 1px solid black;
text-align: center;
}
.add {
padding: 5px;
border: 1px solid black;
margin-bottom: 10px;
}
</style>
</head>
<body>
<div id="app" v-cloak>
<div class="add">
品牌名称:
<input type="text" v-model="name" v-focus>
<input type="button" value="添加" @click=addItem()>
</div>
<div class="add">
品牌名称:
<input type="text" placeholder="请输入搜索条件" v-model="searchVal">
</div>
<div>
<table class="tb">
<tr>
<th>编号</th>
<th>品牌名称</th>
<th>创立时间</th>
<th>操作</th>
</tr>
<tr v-for="(v,i) in list" :key="i">
<td>{{i+1}}</td>
<td>{{v.name}}</td>
<td>{{v.date | fmtDate}}</td>
<td>
<a href="#" @click.prevent="deleItem(v.id)">删除</a>
</td>
</tr>
<!-- v-if="条件表达式" -->
<tr v-if="list.length===0">
<td colspan="4">没有品牌数据</td>
</tr>
</table>
</div>
</div>
<script src="./vue.js"></script>
<script src="./moment.js"></script>
<script src="./axios.min.js"></script>
<script>
// 全局自定义指令
Vue.directive("focus", {
inserted: function (el) {
el.focus();
}
});
// 全局过滤器
Vue.filter("fmtDate", function (v) {
return moment(v).format('YYYY-MM-DD hh:mm:ss');
});
new Vue({
el: "#app",
data: {
searchVal: "",
name: "",
list: []
},
watch: {
searchVal(newV, oldV) {
axios
.get('http://localhost:3000/brands?name_like=' + newV)
.then((res) => {
console.log(11);
// 关键字改变,请求地址发生改变,接着把结果数据赋值给list[]
this.list = res.data;
})
}
},
// 数据加载完后自动调用
computed: {
newlist() {
// return this.list.filter((v) => {
// return v.name.startsWith(this.searchVal)
// });
var temp = [];
axios.get('http://localhost:3000/brands?name_like=' + this.searchVal)
.then((res, callback) => {
temp = res.data;
})
// 在异步操作的外面获得异步操作里面函数的结果
return temp;
}
},
mounted() {
this.getData();
},
methods: {
// 获取数据
getData() {
axios
.get('http://localhost:3000/brands')
.then((res) => {
const { status, data } = res;
if (status === 200) {
this.list = data;
}
})
.cathc((err) => {
})
},
deleItem(ID) {
if (confirm("Sure?")) {
// this.list.splice(index, 1);
axios.delete('http://localhost:3000/brands/' + ID)
.then((res) => {
console.log(res);
this.getData()
})
}
},
addItem() {
axios
.post('http://localhost:3000/brands', {
name: this.name,
date: new Date()
})
.then((res) => {
const { status } = res;
if (status === 201) {
this.getData()
}
})
this.list.unshift({
name: this.name,
date: new Date()
});
this.name = "";
}
}
});
</script>
<!-- <script>
var arr = [1, 2, 3].filter(function (v) {
// console.log(v);
return v > 1
});
</script> -->
</body>
</html>
网友评论