vue 基础学习 一
1. vue 使用快速入门三步走
(1) 新建 HTML 页面,引入 Vue.js文件
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Vue.js 入门示例</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head>
(2) 在JS代码区域,创建Vue核心对象,进行数据绑定
new Vue({
el: "#app",
data() {
return {
name: ""
}
}
});
创建 Vue 对象时,传递一个 js 对象,该对象中需要如下属性:
el: 用来指定哪些标签受 Vue 管理。 该属性取值#app中的app需要是受管理的标签的id属性值data:用来定义数据模型methods:用来定义函数。这个我们在后面就会用到
(3) 编写视图,绑定数据和方法
<div id="app">
<p>{{ message }}</p>
<button v-on:click="greet">Greet</button>
</div>
2. vue 常见指令及作用
常用的指令有
| 指令 | 作用 |
|---|---|
| v-bind | 为HTML标签绑定属性值,如设置 href , css样式等 |
| v-model | 在表单元素上创建双向数据绑定 |
| v-on | 为HTML标签绑定事件 |
| v-if | 条件性的渲染某元素,判定为true时渲染,否则不渲染 |
| v-else | 条件性的渲染某元素,判定为true时渲染,否则不渲染 |
| v-else-if | 条件性的渲染某元素,判定为true时渲染,否则不渲染 |
| v-show | 根据条件展示某元素,区别在于切换的是display属性的值 |
| v-for | 列表渲染,遍历容器的元素或者对象的属性 |
3. vue 生命周期
生命周期的八个阶段:每触发一个生命周期事件,会自动执行一个生命周期方法,这些生命周期方法也被称为钩子方法。
| 状态 | 阶段周期 |
|---|---|
| beforeCreate | 创建前 |
| created | 创建后 |
| beforeMount | 载入前 |
| mounted | 挂载完成 |
| beforeUpdate | 更新前 |
| updated | 更新后 |
| beforeDestroy | 销毁前 |
| destroyed | 销毁后 |
下图是 Vue 官网提供的从创建 Vue 到效果 Vue 对象的整个过程及各个阶段对应的钩子函数
这些钩子方法重点关注 mounted,也最常使用。
mounted:挂载完成,Vue初始化成功,HTML页面渲染成功。而以后我们会在该方法中发送异步请求,加载数据。
小案例
列表查询
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!-- 页面标题 -->
<h1>欢迎你</h1>
<!-- 新增按钮 -->
<input type="button" value="新增" id="add"><br>
<hr>
<!-- Vue.js应用 -->
<div id="app">
<!-- 数据表格 -->
<table border="1" cellspacing="0" width="1200">
<!-- 表头 -->
<tr>
<th>序号</th>
<th>品牌名称</th>
<th>企业名称</th>
<th>排序</th>
<th>品牌介绍</th>
<th>状态</th>
<th>操作</th>
</tr>
<!-- 利用v-for指令循环渲染品牌数据 -->
<tr v-for="(brand,i) in brands" align="center">
<!-- 序号 -->
<td>{{i + 1}}</td>
<!-- 品牌名称 -->
<td>{{brand.brandName}}</td>
<!-- 企业名称 -->
<td>{{brand.companyName}}</td>
<!-- 排序 -->
<td>{{brand.ordered}}</td>
<!-- 品牌介绍 -->
<td>{{brand.description}}</td>
<!-- 状态 -->
<td>{{brand.status == 1 ? "启用" : "禁用"}}</td>
<!-- 操作 -->
<td>
<a href="#">修改</a>
<a href="#">删除</a>
</td>
</tr>
</table>
</div>
<!-- 引入Vue.js库 -->
<script src="js/vue.js"></script>
<!-- 引入Axios库 -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
new Vue({
// Vue实例挂载到id为"app"的元素上
el: "#app",
data() {
return {
// 品牌数据列表
brands: []
}
},
// 在Vue实例挂载后执行的代码
mounted() {
var _this = this;
// 发起GET请求获取数据
axios({
method: "get",
url: "http://localhost:8080/brand_demo/selectAllServlet"
}).then(function (resp) {
// 将获取的数据赋值给brands数组
_this.brands = resp.data;
})
}
})
</script>
</body>
</html>

浙公网安备 33010602011771号