1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
| <template> <div class="row"> <div class="column"> <table> <thead> <tr> <th>标题</th> <th>作者</th> <th>内容</th> <th></th> </tr> </thead> <tbody> <tr v-for="item in ly_list" :key="item.url"> <td>{{ item.title }}</td> <td>{{ item.author }}</td> <td>{{ item.content }}</td> <td> <button @click="editLyb(item)" style="margin: 0.5rem" > 编辑 </button> <button @click="deleteLyb(item)">删除</button> </td> </tr> </tbody> </table> </div> <div class="column"> <input type="hidden" v-model="lyb.url" /> <div> <label for="title">标题</label ><input type="text" id="title" v-model="lyb.title" /> </div> <div> <label for="author">作者</label ><input type="text" id="author" v-model="lyb.author" /> </div> <div> <label for="content">内容</label ><textarea id="content" v-model="lyb.content"></textarea> </div> <button @click="saveLyb">确定</button> </div> </div> </template>
<script> import axios from "axios"; import { reactive, onMounted, toRefs } from "vue";
export default { name: "Lyb", setup() { let base_url = "http://localhost:8000/api/lyb/";
const lyb_blank = { url: "", title: "", author: "", content: "" };
const state = reactive({ ly_list: [], lyb: Object.assign({}, lyb_blank), });
const getLyb = () => { axios .get(base_url) .then((res) => { state.ly_list = res.data; state.lyb = Object.assign({}, lyb_blank); }) .catch((err) => { console.log(err); }); };
const editLyb = (item) => { state.lyb.url = item.url; state.lyb.title = item.title; state.lyb.author = item.author; state.lyb.content = item.content; };
const deleteLyb = (item) => { axios .delete(item.url) .then(() => { getLyb(); }) .catch((err) => { console.log(err); }); };
const saveLyb = () => { let newLyb = { title: state.lyb.title, author: state.lyb.author, content: state.lyb.content, };
if (!state.lyb.url) { axios .post(base_url, newLyb) .then(() => { getLyb(); }) .catch((err) => { console.log(err); }); } else { axios .put(state.lyb.url, newLyb) .then(() => { getLyb(); }) .catch((err) => { console.log(err); }); } };
onMounted(() => { getLyb(); });
return { ...toRefs(state), editLyb, saveLyb, deleteLyb, }; }, }; </script>
|