目录
在开发过程中,我们可以将页面中 某一部分 的功能编写成一个组件,然后再在页面上进行引用。
有利于划分功能模块的开发(HTML、CSS、JavaScript等相关代码都集成到组件中)。
有利于重用
一、局部组件
需要挂载
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="./js/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
<div id="app">
<h1>=======当前页面=======</h1>
{{name}}
<h1>=======引入子组件=======</h1>
<Demo></Demo>
<!-- 可以重复引用 -->
<Demo></Demo>
<Bb></Bb>
<Bb></Bb>
<hr/>
<Bb></Bb>
</div>
<script>
//创建子组件
const Demo = {
data:function() {
return {
msg: '起飞了'
}
},
template: `
<div>
<h1>{{msg}}</h1>
<input type="text" v-model="msg"/>
<input type="button" @click="showMeg" value="点我呀">
</div>
`,
methods: {
showMeg: function () {
alert(this.msg);
}
}
}
//创建子组件
const Bili = {
// 组件中的data是一个方法,并返回值(与Vue对象创建不同)
data:function() {
return {
dataList: [
{"id": 1, "title": "为中华而崛起"},
{"id": 2, "title": "俄乌战争何时休"},
]
}
},
template: `
<div>
<h1>数据列表</h1>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>标题</th>
</tr>
</thead>
<tbody>
<tr v-for="item in dataList">
<td>{{item.id}}</td>
<td>{{item.title}}</td>
</tr>
</tbody>
</table>
</div>
`
}
var app = new Vue({
el: '#app',
data: {
name: "春天的菠菜",
},
components: {
Demo,
Bb: Bili
},
methods: {}
})
</script>
</body>
</html>
二、全局组件
无需挂载直接使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="./js/vue.min.js"></script>
</head>
<body>
<div id="app">
<h1>=======当前页面=======</h1>
{{name}}
<h1>=======引入子组件=======</h1>
<Demo></Demo>
<Demo></Demo>
<Bili></Bili>
<Bili></Bili>
</div>
<script>
//创建子组件
Vue.component('Demo', {
data: function () {
return {
msg: '起飞'
}
},
template: `
<div>
<h1>{{msg}}</h1>
<input type="text" v-model="msg"/>
<input type="button" @click="showMeg" value="点我呀">
</div>
`,
methods: {
showMeg: function () {
alert(this.msg);
}
}
});
//创建子组件
Vue.component('Bili', {
// 组件中的data是一个方法,并返回值(与Vue对象创建不同)
data: function () {
return {
dataList: [
{"id": 1, "title": "为中华崛起而读书"},
{"id": 2, "title": "俄乌战争何时休"},
]
}
},
template: `
<div>
<h1>数据列表</h1>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>标题</th>
</tr>
</thead>
<tbody>
<tr v-for="item in dataList">
<td>{{item.id}}</td>
<td>{{item.title}}</td>
</tr>
</tbody>
</table>
</div>
`
});
var app = new Vue({
el: '#app',
data: {
name: "菠菜",
},
methods: {}
})
</script>
</body>
</html></html>