1.介绍
组件(Component)是 Vue.js 最强大的功能之一。
组件可以扩展 HTML 元素,封装可重用的代码。
注册一个全局组件语法格式如下:Vue.component(tagName,options);tagName 为组件名,options 为配置选项
2.全局组件
2.1 html结构
texts 是自定义组件 ,message为属性名,该属性名不可为大写,需要小写。
<div id="app">
<texts class="text" message="自定义全局组件并通过props传递数据给子组件"></texts>
</div>
2.2 css样式
<style>
*{
margin: 0;
padding: 0;
}
body{
font-family: Verdana,Arial,Helvetica,sans-serif;
font-size: 12px;
color: #222222;
}
#app{
text-align: center;
}
</style>
2.3 javascript逻辑
<script>
// 注册组件 全局组件
Vue.component('texts', {
/**
* prop 是父组件用来传递数据的一个自定义属性。
* 父组件的数据需要通过 props 把数据传给子组件,子组件需要显式地用 props 选项声明 "prop"
*/
props:['message'],
template: '<h3>{{message}}</h3>'
})
// 创建根实例
new Vue({
el: '#app',
})
</script>
3.局部组件
3.1 html结构
<div id="app">
<images class="image"></images>
</div>
3.2 css样式
*{
margin: 0;
padding: 0;
}
body{
font-family: Verdana,Arial,Helvetica,sans-serif;
font-size: 12px;
color: #222222;
}
3.3 javascript逻辑
<script>
//局部组件
var child = {
template:
'<img src="./src/assets/logo.png" alt="">'
}
// 创建根实例
new Vue({
el:
'#app',
components:{
//只能在父布局中使用
'images':
child,
},
})
</script>
4.props 传值
4.0 props动态传值
prop 是父组件用来传递数据的一个自定义属性。
父组件的数据需要通过 props 把数据传给子组件,子组件需要显式地用 props 选项声明 "prop":
动态传值,类似于用 v-bind 绑定 HTML 特性到一个表达式,也可以用 v-bind 动态绑定 props 的值到父组件的数据中。每当父组件的数据变化时,该变化也会传导给子组件:
4.1 html
<div id="app">
<input v-model="parentMessage">
<child v-bind:message="parentMessage"></child>
</div>
4.2 css
*{
margin: 0;
padding: 0;
}
body{
font-family: Verdana,Arial,Helvetica,sans-serif;
font-size: 12px;
color: #222222;
}
#app{
text-align: center;
}
4.3 javascript
<script>
//动态props
Vue.component('child',{
props:['message'],
template:'<span>{{message}}</span>'
})
// 创建根实例
new Vue({
el: '#app',
data:{
parentMessage:'父组件内容',
},
})
</script>
5.自定义事件
5.0 介绍
父组件是使用 props 传递数据给子组件,但如果子组件要把数据传递回去,就需要使用自定义事件!
我们可以使用 v-on 绑定自定义事件, 每个 Vue 实例都实现了事件接口(Events interface),即:
使用 $on(eventName) 监听事件使用 $emit(eventName) 触发事件
另外,父组件可以在使用子组件的地方直接用 v-on 来监听子组件触发的事件。
5.1 html
<div id="app">
<p>{{total}}</p>
<buttons v-on:increment="incrementTotal"></buttons>
</div>
</div>
5.2 css
*{
margin: 0;
padding: 0;
}
body{
font-family: Verdana,Arial,Helvetica,sans-serif;
font-size: 12px;
color: #222222;
}
#app{
text-align: center;
}
5.3 javascript
<script>
/**
* 自定义事件
* 父组件是使用 props 传递数据给子组件,但如果子组件要把数据传递回去,就需要使用自定义事件!
* 使用 v-on 绑定自定义事件, 每个 Vue 实例都实现了事件接口(Events interface),即:
* 使用 $on(eventName) 监听事件
* 使用 $emit(eventName) 触发事件
* 父组件可以在使用子组件的地方直接用 v-on 来监听子组件触发的事件。
*/
Vue.component('buttons',{
template: '<button v-on:click="increment">{{ counter }}</button>',
data:function () {
return {
counter:0,
}
},
methods:{
increment:function () {
this.counter += 1;
this.$emit('increment')
}
},
})
// 创建根实例
new Vue({
el: '#app',
data:{
total:0,
},
methods:{
incrementTotal:function () {
this.total += 1
}
}
})
</script>