<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="example">
<p>{{msg}}</p>
<my-component v-if="showCom"></my-component>
</div>
<script type="text/javascript">
Vue.component('my-component',{
beforeCreate:function(){
console.log("组件准备创建");
},
created:function(){
console.log("组件创建完毕");
},
beforeMount:function(){
console.log("准备挂载");
},
mounted(){
console.log("挂载完毕");
},
beforeUpdate:function(){
console.log("准备更新");
},
updated:function(){
console.log("更新完毕");
},
beforeDestroy:function(){
console.log("开始销毁");
},
destroyed(){
console.log("已销毁");
},
data:function(){
return {count:1}
},
methods:{
updateCount(){
this.count++;
}
},
template:`
<div>
<p>{{count}}</p>
<button @click="updateCount">按钮</button>
</div>
`
});
new Vue({
el:'#example',
created:function(){
console.log("Vue 创建完毕");
},
mounted:function(){
console.log("Vue 挂载完毕");
setTimeout(/*function(){
console.log(this); //指向window
this.showCom=false;
}*/()=>{ //使内外作用域一致
this.showCom=false;
},2000);
},
data:{
msg:'VueJS is Awesome',
showCom:true
}
});
</script>
</body>
</html>
小应用:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="example">
<p>{{msg}}</p>
<text-title></text-title>
</div>
<script type="text/javascript">
Vue.component('text-title',{
mounted(){
console.log("组件挂载完毕");
setInterval(()=>{
this.opacityValue+=0.1;
if(this.opacityValue>1){
this.opacityValue=0.1;
}
},500);
},
data:function(){
return {opacityValue:0}
},
template:`<h1 :style="{opacity:opacityValue}">test</h1>`
});
new Vue({
el:'#example',
data:{
msg:'VueJS is Awesome'
}
});
</script>
</body>
</html>