axios.defaults.baseURL = 'http://localhost:8080/book/'; var vm = new Vue({ el: '#app', data: { id: '', bookName:'', flag: false, submitFlag: false, books: [] }, methods:{ handle: async function () { //编辑 var book = { id: this.id, bookName: this.bookName }; await axios.put(book.id, book); await this.queryBooks(); this.id = ''; this.bookName = ''; this.flag = false; }, //编辑处理 toEdit: async function (id) { var response = await axios.get(id); this.id = response.data.id; this.bookName = response.data.bookName; this.flag = true; }, deleteBook: async function (id) { }, queryBooks: async function () { var response = await axios.get(); this.books = response.data; } }, computed:{ total: function () { return this.books.length; } }, watch: { name: function (val) { console.log(val); } }, mounted:function () { this.queryBooks(); } });补全代码
时间: 2024-03-26 11:37:43 浏览: 51
这段代码已经是一个完整的 Vue.js 组件,如果你想在页面中使用这个组件,需要在 HTML 中引入 Vue.js 库,并在页面中添加一个元素作为 Vue.js 组件的挂载点。示例代码如下:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Vue.js 组件</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<table>
<thead>
<tr>
<th>ID</th>
<th>书名</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(book, index) in books" :key="index">
<td>{{ book.id }}</td>
<td>{{ book.bookName }}</td>
<td>
<button @click="toEdit(book.id)">编辑</button>
<button @click="deleteBook(book.id)">删除</button>
</td>
</tr>
</tbody>
</table>
<div v-if="flag">
<input type="text" v-model="bookName">
<button @click="handle">保存</button>
</div>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
id: '',
bookName: '',
flag: false,
submitFlag: false,
books: []
},
methods: {
handle: async function () {
// 编辑
var book = {
id: this.id,
bookName: this.bookName
};
await axios.put(book.id, book);
await this.queryBooks();
this.id = '';
this.bookName = '';
this.flag = false;
},
// 编辑处理
toEdit: async function (id) {
var response = await axios.get(id);
this.id = response.data.id;
this.bookName = response.data.bookName;
this.flag = true;
},
deleteBook: async function (id) {
// 删除
if (confirm('确定删除该书吗?')) {
await axios.delete(id);
await this.queryBooks();
}
},
queryBooks: async function () {
var response = await axios.get();
this.books = response.data;
}
},
computed: {
total: function () {
return this.books.length;
}
},
watch: {
name: function (val) {
console.log(val);
}
},
mounted: function () {
this.queryBooks();
}
});
</script>
</body>
</html>
```
在上面的示例代码中,我们使用了 Vue.js 的模板语法来渲染表格和表单,使用了 `v-for` 指令来循环渲染每一行数据,使用了 `v-if` 指令来判断表单是否需要显示。在 Vue.js 组件中,我们可以使用 `data` 属性来定义组件的数据,使用 `methods` 属性来定义组件的方法,使用 `computed` 属性来定义组件的计算属性,使用 `watch` 属性来监听组件的数据变化,使用 `mounted` 生命周期钩子来在组件挂载后执行一些操作。
阅读全文