通过学习基础的vue语法,vue真是强大,原本需要我们在js实现的操作,都被简化到极致,就比如循环,分支以及事件绑定。下面我们来演示下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
<script type="text/javascript" src="vue.js"></script>
</head>
<style type="text/css">
fieldset{
width:600px;
margin:0px auto;
text-align:center;
}
</style>
<body>
<fieldset>
<legend>商品列表</legend>
<table id="example" border="1" width="100%">//id要与下面的组件el中的定义的名字保持一致才能调用其中的属性和方法
<thead>
<tr>
<th>id</th>
<th>名称</th>
<th>单价</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="elem in newfruit">// forEach循环遍历newfruit数组
<td>{{elem.id}}</td>
<td>{{elem.name}}</td>
<td>{{elem.price}}</td>
<td><input type="button" value="添加" v-on:click="addElement"></td>//单击事件绑定example中的函数addElement
</tr>
</tbody>
</table>
</fieldset>
</body>
<script type="text/javascript">
var fruit= [{"id":"1001","name":"橘子","price":"2.0"},
{"id":"1001","name":"橘子","price":"2.0"},
{"id":"1001","name":"橘子","price":"2.0"}];
var vm=new Vue({
el:"#example",
data:{
message:"hello world!",
newfruit:fruit//让newfruit和fruit指向数组 当用newfruit或fruit修改数组中的数据时,都将改变原数组。
},
methods:{
addElement:function(){
this.newfruit.push({"id":"1001","name":"橘子","price":"2.0"});
console.log(fruit)
},
},
//生命周期钩子
created:function(){
//实例创建后调用
console.log(this.message);
}
})
// $watch 是一个实例方法
vm.$watch('newfruit', function (newValue, oldValue) {
// 这个回调将在 `vm.newfruit` 改变后调用
console.log("函数被调用")
})
// Object.freeze(vm)//添加后不允许改变vm组件里的值
</script>
</html>
可以看到hello world!在实例创建后就被调用了,create是在实例创建后就被调用了。
<body>
<div class="p1">
<p>{{date}}</p>
<ul>
<li v-for="item in fruit">
<ul>
<li v-for="value in item">{{value}}</li>
</ul>
</li>
</ul>
</div>
</body>
<script type="text/javascript">
var vm=new Vue({
el:document.querySelector(".p1"),
data:{
message:"this is a alert",
date:new Date(),
fruit: [{"id":"1001","name":"橘子","price":"2.0"},
{"id":"1001","name":"橘子","price":"2.0"},
{"id":"1001","name":"橘子","price":"2.0"}]
},
mounted:function(){
var _this=this;
this.timer=setInterval(function(){
_this.date=new Date();
},1000)
},
methods:{
handleOnclick:function(){
alert("33334");
}
},
beforeDestory:function(){
if(this.timer){
clearInterval(this.timer);
}
}
})
</script>
v-for不仅可以遍历数组,也可以遍历对象。
create 实例创建完成后调用,此阶段完成了数据的观测等,但尚未挂载,$el还不可用。需要初始化处理一些数据时会比较有用。
mounted el挂载到实例上后调用,一般我们的第一个业务逻辑会在这里开始。
beforeDestroy 实例销毁之前调用。主要解绑一些使用addEventListener监听的事件等。
同样的钩子还有updated和destroyed等。
vue组件的生命周期图:
我们可以从图中清晰看到每一个生命周期钩子在哪个阶段才会被调用。