[improvement] Sidebar: use relation mixin

This commit is contained in:
陈嘉涵 2019-05-06 20:37:09 +08:00
parent 8de7a287f6
commit 9c6c10fdcd
3 changed files with 13 additions and 33 deletions

View File

@ -5,6 +5,10 @@ export function ChildrenMixin(parent) {
computed: { computed: {
parent() { parent() {
return this[parent]; return this[parent];
},
index() {
return this.parent.children.indexOf(this);
} }
}, },

View File

@ -1,43 +1,28 @@
import { use } from '../utils'; import { use } from '../utils';
import Info from '../info'; import Info from '../info';
import { ChildrenMixin } from '../mixins/relation';
const [sfc, bem] = use('sidebar-item'); const [sfc, bem] = use('sidebar-item');
export default sfc({ export default sfc({
mixins: [ChildrenMixin('vanSidebar')],
props: { props: {
url: String, url: String,
info: [String, Number], info: [String, Number],
title: String title: String
}, },
inject: ['vanSidebar'],
created() {
this.parent.items.push(this);
},
beforeDestroy() {
this.parent.items = this.parent.items.filter(item => item !== this);
},
computed: { computed: {
parent() {
if (process.env.NODE_ENV !== 'production' && !this.vanSidebar) {
console.error('[Vant] SidebarItem needs to be child of Sidebar');
}
return this.vanSidebar;
},
select() { select() {
return this.parent.items.indexOf(this) === +this.parent.activeKey; return this.index === +this.parent.activeKey;
} }
}, },
methods: { methods: {
onClick() { onClick() {
const index = this.parent.items.indexOf(this); this.$emit('click', this.index);
this.$emit('click', index); this.parent.$emit('change', this.index);
this.parent.$emit('change', index);
} }
}, },

View File

@ -1,8 +1,11 @@
import { use } from '../utils'; import { use } from '../utils';
import { ParentMixin } from '../mixins/relation';
const [sfc, bem] = use('sidebar'); const [sfc, bem] = use('sidebar');
export default sfc({ export default sfc({
mixins: [ParentMixin('vanSidebar')],
props: { props: {
activeKey: { activeKey: {
type: [Number, String], type: [Number, String],
@ -10,18 +13,6 @@ export default sfc({
} }
}, },
provide() {
return {
vanSidebar: this
};
},
data() {
return {
items: []
};
},
render(h) { render(h) {
return <div class={[bem(), 'van-hairline--top-bottom']}>{this.slots()}</div>; return <div class={[bem(), 'van-hairline--top-bottom']}>{this.slots()}</div>;
} }