初识组件Component
组件(Component)是 Vue.js 最强大的功能之一。(数据驱动)
VueComponente的实例对象,简称vc(组件实例对象)。
Vue的实例对象,简称vm。
定义一个组件
<div id="show">
<showbox></showbox> //复用
<showbox></showbox> //每用一次组件,就会有一个它的新实例被创建
<showbox></showbox> //点击按钮时,每个组件都会各自独立维护它的数据
</div>
<script>
new Vue({ el: '#show' }) // Vue 根实例中,把这个组件作为自定义元素来使用
Vue.component('showbox', { 定义一个名为 showbox 的新组件
data: function () {
return {
num: 0
}
},
template: '<button v-on:click="num++">{{ num }} </button>'
})
</script>
一个组件的 data 选项必须是一个函数,所以每个实例才可以维护一份被返回对象的独立的拷贝
组件的嵌套
首屏渲染,父子组件生命周期的执行顺序?
先执行父组件的
beforeCreate created beforemount->父组件
beforeCreate created beforemount mounted->子组件
mounted--父组件
父子组件的销毁过程呢?
beforeUpdate-----父组件
beforeDestroy destroyed---子组件
updated---父组件
(三层销毁过程) father->son(被销毁的子组件)->grandson
beforeupdate----father
beforeDestroy---son
beforeDestroy desto再yed--grandson
destoryed---son
updated---father
父组件向子组件传值
父组件通过自定义属性(:属性名=“data中数据”)绑定数据
子组件通过配置 (props:[“属性名”])接受父组件传来的数据
子组件向父组件传值
父组件绑定自定义事件(@自定义事件名=“方法”)
子组件使用 vm.$emit(“自定义事件名”,数据)给父组件传值
访问父子组件的值
子访问父:$paren $root 访问父方法
父访问子:$children $refs
多层组件传值
$listeners
$attrs
动态组件
要进行页面中不同组件之间进行动态切换,vue除了条件渲染,还可以使用动态组件。
component 标签的 is属性语法:is后跟组件的变量名决定使用哪个组件来渲染
例:
<component :is="status === 1 ? 'HelloWorld' : 'CSDN'" ></component>