基本使用
- 在script里面调用写组件
- 定义组件:const stuschool = Vue.extend({})
- 注册全局组件: Vue.component('stuschool', stuschoole)(使用组件的名字,引入定义组件名字)
- 注册局部组件: new Vue({ components:{ stuschool:stuschool }})
- 使用组件在html里面直接使用 <stuschool> </stuschool>
-
el不要写--为什么? --最终所有的组件都要经过一个vm的管理,由vm中的el决定服务那个容器
-
data必须写成函数--为什么? -- 避免组件被复用,数据存在引用的关系
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../js/vue.js"></script>
</head>
<body>
<!-- 都可以重复调用 -->
<div id="root">
<!-- 使用学校的注册组件 -->
<stuschool></stuschool>
<stuschool></stuschool>
<hr>
<!-- 使用学生的注册组件 -->
<stustudent></stustudent>
<stustudent></stustudent>
<hr>
<!-- 调用全局 -->
<hello></hello>
</div>
<script>
// 第一步 定义组件 学校
const stuschool = Vue.extend({
template: `
<div>
<h2>{{name}}</h2>
<h2>{{address}}</h2>
<button @click='add'>点击</button>
</div>
`,
data() {
return {
name: "厚溥",
address: "中兴大街"
}
},
methods: {
add() {
alert("点击被显示出来")
}
}
})
// 第一步 定义组件 学生
const stustudent = Vue.extend({
template: `
<div>
<h2>{{name}}</h2>
<h2>{{age}}</h2>
</div>
`,
data() {
return {
name: "张三",
age: 18
}
}
})
// 第一步 定义全局组件
const quanju = Vue.extend({
template: `
<div>
<h2>{{name}}</h2>
<h2>{{age}}</h2>
</div>
`,
data() {
return {
name: "张四",
age: 90
}
}
})
// 第二部 注册全局组件
Vue.component('hello', quanju)
// 第二部 注册组件
new Vue({
el: "#root",
data: {
},
components: {
// 学校
stuschool: stuschool,
stustudent: stustudent
},
methods: {
// add
},
})
</script>
</body>
</html>
VueComponent的实例对象,简称vc :组件的实例对象
Vue的实例对象简称为vm
组件名的注意点:了解