组件的封装

it2024-08-19  45

1.父组件传值到子组件(props)  2.子组件传值到父组件($emit) 3.插槽使用(slot)。对于一个独立的组件,props是用来为组件内部注入核心内容;$emit用来使这个组件通过一些操作来融入其它组件中。

1.首先,可以看到前端工程下有一个components目录,在components下新建一个文件夹xx-button,再在xx-button下创建一个index.vue文件

2.然后在index.vue中写自己的代码。为了规范,注意代码中的name命名XxButton,以后使用的组件就是XxButton:

<template>  <el-button-group>   <el-button v-for="(btn,index) in this.buttons" :key="index" :type="btn.type ? btn.type:'primary'"    :icon="btn.icon" :size="btn.size?btn.size:'mini'" @click="btn.click">{{btn.label}}</el-button>  </el-button-group> </template>    <script> export default {  name: 'XxButton', // 注意这里的name命名,就是你以后封装好后使用的组件名  props: {   buttons: {    type: Array,    required: true   }  } } </script>

3.然后在components下还有一个index.js文件,咱们要在index.js中注册上自己定义的组件:

import XxButton from './xx-button'    Vue.component(XxButton.name, XxButton)

注意:这个index.js也一定要在main.js中引入,不然就无法使用。当然,你也可以直接在main.js中直接注册组件,这里为了便于组件的统一管理,就在components下建了一个index.js来统一注册组件。

import './components/index'

4.最后,在页面开发中

<XxButtom :buttom ='this.button'></XxButton>

button: [ { label:'删除', icon:‘el-del’ click:this.del }, { label:'编辑', icon:‘el-edit’ click:this.add } ]

 

最新回复(0)