Vue CLI(脚手架)
Vue CLI 是一个基于 Vue.js 进行快速开发的完整系统
安装
npm install -g @vue/cli
使用vue -V
查看版本,确认是否安装成功
创建项目
vue create 项目名
选择版本及配置
我们选择第三个自定义版本
选择需要的特性
以上选择的分别是
- 选择Vue的版本
- js高级语法转换
- Router路由
选择版本
这里选择的是 vue 2
路由
这里选择的是no
配置文件
选择YES
是否保存记录
选择NO
打开项目
cd hello-vue
npm run serve
项目结构
项目实践
项目要求:表格的CURD
-
首先删除多余的文件
-
创建添加、编辑、详情页的组件
-
修改路由
import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../views/Home.vue' import Add from '../views/Add.vue' import Edit from '../views/Edit.vue' import Detail from '../views/Detail.vue' Vue.use(VueRouter) const routes = [{ path: '/', name: 'Home', component: Home }, { path: '/add', name: 'Add', component: Add }, { path: '/edit/:id', name: 'Edit', component: Edit }, { path: '/detail/:id', name: 'Detail', component: Detail }, ] const router = new VueRouter({ routes }) export default router
-
在Home页创建表格
<template> <div class="home"> <router-link to="添加"></router-link> <table> <thead> <tr> <th>编号</th> <th>标题</th> <th>内容</th> <th>创建时间</th> <th>操作</th> </tr> </thead> <tbody> <tr :key="item.id" v-for="item in posts"> <td>{{ item.id }}</td> <td>{{ item.title }}</td> <td>{{ item.content }}</td> <td>{{ item.create_time }}</td> <td> <router-link :to="{ name: 'Detail', params: { id: item.id } }" >详情</router-link > <router-link :to="{ name: 'Edit', params: { id: item.id } }" >编辑</router-link > <a href="#">删除</a> </td> </tr> </tbody> </table> </div> </template> <script> export default { name: "Home", data() { return { posts: [ { id: 1, title: "测试标题一", content: "测试内容一", create_time: 1615446491112, }, ], }; }, }; </script>
效果:
使用axios连接后台接口
安装axios
npm install axios
在组件中引入
import axios from "axios";
获取列表
created() {
axios.get("http://127.0.0.1:3000/api/v1/posts").then((res) => {
this.posts = res.data.data;
console.log(res);
});
},
添加数据
add() {
axios.post("http://127.0.0.1:3000/api/v1/posts", {
title: this.title,
content: this.content,
})
.then((res) => {
var data = res.data;
if (data.errno == 0) {
alert("添加成功");
this.title = "";
this.content = "";
//路由重定向
this.$router.push("/");
}
});
}
删除数据
del(id) {
axios.delete(`http://127.0.0.1:3000/api/v1/posts/${id}`).then((res) =>
if (res.data.errno == 0) {
//findIndex返回的值是匹配当前项的索引值
var index = this.posts.findIndex((item) => {
return item.id == id;
});
this.posts.splice(index, 1);
alert(res.data.msg);
}
});
},
},
修改数据
edite() {
//获取获取vue-router传递的参数
var id = this.$route.params.id;
axios
.put(`http://127.0.0.1:3000/api/v1/posts/${id}`, {
title: this.title,
content: this.content,
})
.then((res) => {
if (res.data.errno == 0) {
alert(res.data.msg);
this.$router.push("/");
}
});
},
查询数据
created() {
var id = this.$route.params.id;
axios.get(`http://127.0.0.1:3000/api/v1/posts/${id}`).then((res) => {
this.post = res.data.data;
});
},