前言
- VUE是前端用的最多的框架;
- 這篇文章是本人大一上學習前端的筆記;
- 歡迎點贊 + 收藏 + 關注,本人將會持續更新。
文章目錄
- 2、Vue組件化編程
- 2.1、組件
- 2.2、基本使用
- 2.2.1、VueComponent
2、Vue組件化編程
2.1、組件
組件:用來實現局部功能的代碼和資源的集合
2.2、基本使用
- 三大步驟:
- 定義組件(常見組件)
- 注冊組件
- 使用組件(寫組件標簽)
<div id="root">//3.寫組件標簽<school></school><student></student>
</div>
<script>//1.創建school組件const school = Vue.extend({//不要寫eltemplate: `<div class="demo"><h2>學校名稱:{{schoolName}}</h2><h2>學校地址:{{address}}</h2> </div>`,data(){return {schoolName: '尚硅谷',address: '北京昌平'}}}),//1.創建student組件const student = Vue.extend({template:`<div><h2>學生姓名:{{studentName}}</h2><h2>學生年齡:{{age}}</h2></div>`,data() {return {studentName: 'cy',age: 20}
}})//創建vmnew Vue({el: '#root',//2.注冊組件(局部注冊)components: {school,student}})
</script>
關于組件名:
- 一個單詞組成
- 第一種寫法(首字母小寫)
- 第二種寫法(首字母大寫)
- 多個單詞組成:
- 第一種寫法:如:my-school
- 第二種寫法:如:MySchool(需要Vue腳手架支持)
注意:組件名盡可能避免HTML已經有的元素名稱
- 關于組件標簽:
- 第一種寫法:
- 第二種寫法:
<body><div id="root"></div>
</body><script type="text/javascript">Vue.config.productionTip = false//定義student組件const student = Vue.extend({template:`<div><h2>學生名稱:{{name}}</h2> <h2>學生年齡:{{age}}</h2> </div>`,data(){return {name:'JOJO',age:20}}})//定義school組件const school = Vue.extend({template:`<div><h2>學校名稱:{{name}}</h2> <h2>學校地址:{{address}}</h2> <student></student></div>`,components:{student},data(){return {name:'尚硅谷',address:'北京'}}})//定義hello組件const hello = Vue.extend({template:`<h1>{{msg}}</h1>`,data(){return {msg:"歡迎學習尚硅谷Vue教程!"}}})//定義app組件const app = Vue.extend({template:`<div><hello></hello><school></school></div>`,components:{school,hello}})//創建vmnew Vue({template:`<app></app>`,el:'#root',components:{app}})</script>
</html>
2.2.1、VueComponent
- school組件本質是一個名為
VueComponent
的構造函數,且不是程序員定義的,是Vue.extend
生成的 - 特別注意:每次調用
Vue.extend
,返回的都是一個全新的VueComponent! - 關于this指向:
- 組件配置中:
data
函數、methods
中的函數、watch
中的函數、computed
中的函數 它們的this均是VueComponent實例對象 - new Vue(options)
配置中:
data函數、
methods中的函數、
watch中的函數、
computed`中的函數 它們的this均是Vue實例對象
- 組件配置中:
VueComponent.prototype.proto === Vue.prototype