VUE-组件
1.组件定义
非单文件组件:
//定义组件
const student = Vue.extend({
//组件名字
name:'student',
//模板内容
template:`
<div>
<h2>学生名称:{{name}}</h2>
<h2>学生名称:{{age}}</h2>
</div>
`,
//数据--data定义必须是函数形式data(){}
data(){
return {
name:'学生',
age:18
}
}
})
//父子组件
const app = Vue.extend({
template:`
<div>
<student></student>
</div>
`,
//注册组件(局部)
components:{
student
}
})
//将组件app挂载到el对应的元素上
new Vue({
template:'<app></app>'
el:'#root',
//注册组件(局部)
components:{
app
}
})
单文件组件模板:
<template>
<div></div>
</template>
<script>
//当前组件可能被引入,所以需要export导出
export default{
name:'vc1',
template:``,
data(){}
}
</script>
<style>
/*组件样式*/
</style>
单文件组件-App.vue模板:
App.vue是主组件(父组件)
<template>
<!--模板结构-->
<div id="app">
<HelloWorld msg="Welcome to Your Vue.js App"/>
</div>
</template>
<script>
/*导入组件*/
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'app',
//子组件
components: {
HelloWorld
}
}
</script>
<style>
#app {}
</style>
2.组件与vm对象的关系
-
每次调用Vue.extend时,返回一个VueComponent对象,组件中,this指VueComponent对象
-
在new Vue(options)配置中,this指vm对象
-
VueComponent.prototype._proto_ = Vue.prototype
VueComponent是Vue中组件的构造函数,它的原型对象的__proto__是Vue函数的原型对象
这样的话,组件对象也能访问到VueComponent