異步操作:
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 { 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>