1、父组件传递到子组件 props
<my-Component title="不做大哥好多年"></my-Component>
<my-component title="左边画条龙"></my-component>
<my-component title="右边画个彩虹"></my-component>
let MyComponent = {
template: '<p>{{title}}</p>',
props: ['title']
};
new Vue({
components: {
MyComponent
}
}).$mount('#app');
传递对象:
<my-Component title="不做大哥好多年" user="{id: 1, username: '孙悟空', age: '500'}"></my-Component>
<my-component title="左边画条龙"></my-component>
<my-component title="右边画个彩虹"></my-component>
let MyComponent = {
template: '<p>{{title}} {{user | json}}</p>',
props: ['title', 'user']
};
new Vue({
components: {
MyComponent
}
}).$mount('#app');
2、slot插槽,显示标签内里的内容
<my-Component title="不做大哥好多年" user="{id: 1, username: '孙悟空', age: '500'}">我是标签内内容</my-Component>
let MyComponent = {
template: '<p>{{title}} {{user | json}}<slot></slot></p>',
props: ['title', 'user']
};
3、子组件向父组件传值 $emit,我们来实现一个效果,点击组件中的一个按钮,控制整个页面的字体大小。可以使用 $emit来触发父组件的事件,控制一个全局的字号变量,来达到控制整个页面字体大小的效果。
<div id="app" :style="{'font-size': fontSize + 'px'}">
<p>我的大小也会变大</p>
<my-Component title="不做大哥好多年" @change-font-size="changeFontSize">我是标签内内容</my-Component>
</div>
let MyComponent = {
template: `<p>{{title}} <button @click="$emit('change-font-size', 0.1)">点我变大字体</button></p>`,
props: ['title']
};
new Vue({
data: function(){
return {
fontSize: 12
}
},
methods:{
changeFontSize: function(step){
this.fontSize += step;
}
},
components: {
MyComponent
}
}).$mount('#app');
4、动态组件,使用<component>配合特殊属性is达到效果
<div id="app">
<p>
<span @click="currentComponent='component1'">组件1</span>
<span @click="currentComponent='component2'">组件2</span>
<span @click="currentComponent='component3'">组件2</span>
</p>
<component :is="currentComponent"></component>
</div>
let component1 = {
template: '<p>我是组件1</p>'
};
let component2 = {
template: '<p>我是组件2</p>'
};
let component3 = {
template: '<p>我是组件3</p>'
};
new Vue({
data(){
return {
currentComponent: 'component1'
}
},
components: {
component1, component2, component3
}
}).$mount('#app');
效果是点击组件1时显示组件1,组件二时显示组件2,达到动态组件的效果。
5、组件上实现v-model,我们知道v-model其实是一个语法糖,通过v-on:input和v-on:input来实现,组件要实现v-model也逃不掉这个原理,子组件中的input事件触发父组件的input事件,并将输入的内容传递出去。
<div id="app">
<my-input v-model="pValue"></my-input>
{{pValue}}
</div>
let MyInput = {
template: `<div><input type="text" :value="value" @input="$emit('input', $event.target.value)"></div>`,
props: ['value']
};
new Vue({
data(){
return {
pValue: 'hello vue'
}
},
components: {
MyInput
}
}).$mount('#app');
6、注意事项
- 组件只能有一个根元素
- 有些组件不能出现在某些组件中,如li不能出现在table中,否则会导出渲染出错
- 但可以使用is属性来避免这个问题,如<table> <tr is="blog-post-row"></tr> </table>
- 在模板字符串、vue文件、在<script type="text/x-template">中则不会出现这个问题