课堂讲义
1、Vue 高级使用
1.1、自定义组件
-
学完了 Element 组件后,我们会发现组件其实就是自定义的标签。例如<el-button>就是对<button>的封装
-
本质上,组件是带有一个名字且可复用的 Vue 实例,我们完全可以自己定义
-
定义格式
Vue.component(组件名称, {
props:组件的属性,
data: 组件的数据函数,
template: 组件解析的标签模板
}) -
代码实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>自定义组件</title>
<script src="vue/vue.js"></script>
</head>
<body>
<div id="div">
<my-button></my-button>
</div>
</body>
<script>
Vue.component("my-button",{
// 属性
props:["style"],
// 数据函数
data: function(){
return{
msg:"我的按钮"
}
},
//解析标签模板
template:"<button style='color:red'>{{msg}}</button>"
});
new Vue({
el:"#div"
});
</script>
</html>
1.2、Vue的生命周期
-
生命周期
-
生命周期的八个阶段
-
代码实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>生命周期</title>
<script src="vue/vue.js"></script>
</head>
<body>
<div id="app">
{{message}}
</div>
</body>
<script>
let vm = new Vue({
el: '#app',
data: {
message: 'Vue的生命周期'
},
beforeCreate: function() {
console.group('------beforeCreate创建前状态------');
console.log("%c%s", "color:red", "el : " + this.$el); //undefined
console.log("%c%s", "color:red", "data : " + this.$data); //undefined
console.log("%c%s", "color:red", "message: " + this.message);//undefined
},
created: function() {
console.group('------created创建完毕状态------');
console.log("%c%s", "color:red", "el : " + this.$el); //undefined
console.log("%c%s", "color:red", "data : " + this.$data); //已被初始化
console.log("%c%s", "color:red", "message: " + this.message); //已被初始化
},
beforeMount: function() {