1、代碼地址 github:https://github.com/MengFangui/VueComponentDemo- 2、關鍵代碼 (1)main.js (2)app.vue (3)button.vue (4)title.vue 3、效果 ...
1、代碼地址
github:https://github.com/MengFangui/VueComponentDemo-
2、關鍵代碼
(1)main.js
//引入vue
import Vue from 'vue';
import App from './app.vue';
var app = new Vue({
el: '#app',
//虛擬DOM
render: h => {
return h(App)
}
});
(2)app.vue
<template>
<div>
<vTitle title='Vue組件化'></vTitle>
<vButton @click='parentHandleClick'>點擊按鈕</vButton>
</div>
</template>
<script>
//導入組件
import vTitle from './views/title.vue';
import vButton from './views/button.vue';
export default {
//局部註冊組件
components: {
vTitle,
vButton
},
methods: {
parentHandleClick(e) {
alert('觸發父組件事件')
}
}
}
</script>
(3)button.vue
<template>
<button @click="childHandleClick" :style="styles">
<!--顯示父元素內容-->
<slot></slot>
</button>
</template>
<script>
export default{
props:{
color:{
type:String,
default:'#00cc66'
}
},
computed:{
styles(){
return {
background:this.color
}
}
},
methods:{
childHandleClick(e){
//觸發父組件的click事件
this.$emit('click',e)
}
}
}
</script>
<style scoped="scoped">
button{
border: 0;
outline: none;
color: #fff;
padding: 4px 8px;
}
button:active{
position: relative;
top: 1px;
left: 1px;
}
</style>
使用import導入css方法:
<style scoped="scoped">
@import '../css/button.css';
</style>
(4)title.vue
<template>
<h1>
<a :href="'#'+title">{{title}}</a>
</h1>
</template>
<script>
export default {
props:{
title:{
type:String
}
}
}
</script>
<style scoped="scoped">
h1 a{
color: red;
font-size: 24px;
}
</style>
3、效果