14-频道组件封装-实现
频道组件封装-实现01-内部功能
-
内部功能的实现
components/my-channel.vue 组件
<template>
<el-select v-model="value" placeholder="请选择" clearable>
<el-option v-for="item in channelOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
</el-select>
</template>
<script>
// 基础功能:结构 数据 获取
export default {
name: 'my-channel',
data () {
return {
// 当前选择频道ID
value: null,
// 频道选项数据
channelOptions: []
}
},
created () {
this.getChannelOptions()
},
methods: {
async getChannelOptions () {
// const {
// data: { data }
// } = await this.$http.get('channels')
const data = { channels: [{ id: 1, name: 'java' }, { id: 2, name: '前端' }] }
this.channelOptions = data.channels
}
}
}
</script>
<style scoped lang='less'></style>
- 全局注册:
components/index.js
import MyBread from '@/components/my-bread'
+import MyChannel from '@/components/my-channel'
export default {
install (Vue) {
Vue.component(MyBread.name, MyBread)
+ Vue.component(MyChannel.name, MyChannel)
}
}
频道组件封装-实现02-v-model实现
- v-model指令功能
- 父传子:
:value
- 子传父:
@input
- 父传子:
**父组件:**渲染显示的页面——src/views/article/index.vue
<!-- 封装的组件 :value="reqParams.channel_id" @input="reqParams.channel_id=接受数据" -->
<my-channel v-model="reqParams.channel_id"></my-channel>
**子组件:**封装的组件——src/components/my-channel.vue
接受父组件数据
// value 数据 仅读
props: ['value'],
<el-select :value="value"
选择过频道数据后,把频道ID提交父组件
<el-select @change="fn"
fn (channelId) {
// channelId 当你清空操作 值是空字符串 改成null
if (channelId === '') channelId = null
// 提交父组件
this.$emit('input', channelId)
},