异步操作:
1.ajax,
2.定时器
3.点击事件
4.数据库操作
特点:代码不等待,后续代码会继续执行。
watch:{ //watch作用监测已经存在的数据 newVal 新值,oldVal 旧值 searchName(newVal,oldVal){ axios.get("http://localhost:3001/brands?name_like="+newVal).then((res) => { const { status, data } = res; if (status === 200) { this.list = data; } }); } },
======================全部代码-如果不是异步操作数据库也可以通过集合中的filter进行过滤搜索=====================================
<template> <div id="HelloWorld"> <div class="add"> 品牌名称: <input type="text" v-model="itemName" /> <input type="button" @click="addItem" value="添加" /> </div> <div class="add"> 品牌名称: <input type="text" placeholder="请输入搜索条件" v-model="searchName" /> <table class="tb"> <tr> <th>编号</th> <th>品牌名称</th> <th>创立时间</th> <th>操作</th> </tr> <tr v-for="(v, i) in list"> <td>{{ v.id }}</td> <td>{{ v.name }}</td> <td>{{ v.date | timeFormat }}</td> <td><a href="#" @click.prevent="deleItem(v.id)">删除</a></td> </tr> <tr> <td v-if="list.length === 0" colspan="4">没有品牌数据</td> </tr> </table> </div> </div> </template> <script> // var list=[{ // name:"TCL", // date:new Date() // }, // { // name:"娃娃", // date:new Date() // },{ // name:"cc", // date:new Date() // } // ] // var list=[] import axios from "axios"; export default { name: "HelloWorld", data() { return { list: [], itemName: "", searchName: "", }; }, mounted() { this.getAllBrands(); }, methods: { //获取数据 getAllBrands() { axios.get("http://localhost:3001/brands").then((res) => { const { status, data } = res; if (status === 200) { this.list = data; } }); }, addItem() { axios .post("http://localhost:3001/brands", { name: this.itemName, date: new Date(), }) .then((res) => { const { status, data } = res; if (status === 201) { this.getAllBrands(); this.itemName=''; } }); }, //删除 deleItem(index) { if (confirm("是否要删除数据?")) { //this.list.splice(index,1); axios.delete("http://localhost:3001/brands/" + index).then((res) => { const { status, data } = res; if (status === 200) { this.getAllBrands(); } }); } }, }, watch:{ //watch作用监测已经存在的数据 newVal 新值,oldVal 旧值 searchName(newVal,oldVal){ axios.get("http://localhost:3001/brands?name_like="+newVal).then((res) => { const { status, data } = res; if (status === 200) { this.list = data; } }); } }, computed: { //过滤,从页面过滤或者从数据库返回结果{{如果不改查询结果的集合是可以查询到模糊查询的数据的。}},异步操作的结果 // fileterList() { // let { searchName, list } = this; // let arr = [...list]; // if (searchName.trim()) { // arr = list.filter((p) => p.name.indexOf(searchName) !== -1); // } // return arr; // }, }, }; </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> #HelloWorld { 600px; margin: 10px auto; } .tb { border-collapse: collapse; 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>