版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/q95548854/article/details/79669287
01-Vue中多层组件通信
<div id="app">
<my-parent :imgtitle="title" :imgsrc="img"></my-parent>
</div>
<template id="my_img">
<img :src="imgsrc" width="200">
</template>
<template id="my_title">
<h2>{{title}}</h2>
</template>
<template id="my_parent">
<div>
<child1 :imgsrc="imgsrc"></child1>
<child2 :title="imgtitle"></child2>
</div>
</template>
<script src="js/vue.js"></script>
<script>
// 1. 子组件的实例
let Child1 = Vue.extend({
template: '#my_img',
props: ['imgsrc']
});
let Child2 = Vue.extend({
template: '#my_title',
props: ['title']
});
// 2. 注册父组件
Vue.component('my-parent', {
props: ['imgtitle', 'imgsrc'],
components: {
'child1': Child1,
'child2': Child2
},
template: '#my_parent'
});
new Vue({
el: '#app',
data: {
title: '我是不是很漂亮',
img: 'img/img_01.jpg'
}
});
</script>
02-Vue的自定义事件
<div id="app">
<my-btn @total="allcounter()"></my-btn>
<my-btn @total="allcounter()"></my-btn>
<my-btn @total="allcounter()"></my-btn>
<my-btn @total="allcounter()"></my-btn>
<my-btn @total="allcounter()"></my-btn>
<my-btn @total="allcounter()"></my-btn>
<my-btn @total="allcounter()"></my-btn>
<p>所有按钮一共点击了{{totalCounter}}次</p>
</div>
<template id="my_btn">
<button @click="total()">点击了{{counter}}次</button>
</template>
<script src="js/vue.js"></script>
<script>
Vue.component('my-btn', {
template: '#my_btn',
data(){
return {
counter: 0
}
},
methods: {
total(){
this.counter += 1;
// 通知外界,我调用了这个方法
this.$emit('total');
}
}
});
new Vue({
el: '#app',
data: {
totalCounter: 0
},
methods: {
allcounter(){
this.totalCounter += 1;
}
}
});
</script>
03-Vue的匿名插槽solt
<div id="app">
<my-slot>
<p>这个姑娘好美呀!</p>
<input type="date">
</my-slot>
</div>
<template id="my_slot">
<div id="panel">
<h2 class="panel-header">插槽的头部</h2>
<!--预留一个插槽-->
<slot>可以替换任何标签,默认显示提示的内容</slot>
<footer>插槽的尾部</footer>
</div>
</template>
<script src="js/vue.js"></script>
<script>
Vue.component('my-slot', {
template: '#my_slot'
});
new Vue({
el: '#app',
data: {
msg: '今天的天气很好!'
}
});
</script>
04-Vue的实名插槽solt
<div id="app">
<my-computer>
<div slot="cpu">Inter Core i8</div>
<img slot="gpu" src="img/img_02.jpg" width="100" alt="">
<div slot="memory">128G</div>
<input type="color" slot="hard-drive">
</my-computer>
</div>
<template id="my_computer">
<div id="main">
<slot name="cpu">这里是插cpu的</slot>
<slot name="gpu">这里是插gpu的</slot>
<slot name="memory">这里是插内存条的</slot>
<slot name="hard-drive">这里是插硬盘的</slot>
</div>
</template>
<script src="js/vue.js"></script>
<script>
Vue.component('my-computer', {
template: '#my_computer'
});
new Vue({
el: '#app',
data: {
msg: '今天的天气很好!'
}
});
</script>