为了账号安全,请及时绑定邮箱和手机立即绑定

请教如何利用JS完成简单的商品筛选问题

请教如何利用JS完成简单的商品筛选问题

三国纷争 2019-03-15 18:15:24
设定一个数组,其中存放有全部商品的名称,并在界面左侧的边框中显示出来2.当用户点击左侧边框中的商品,表示选中该商品,则将该商品从左侧的列表中删除,并添加到右侧的选中列表中; 3.注意,在右侧的选中列表中商品名称要按顺序排序,添加新选中的商品名,也要插入到对应的顺序位置
查看完整描述

3 回答

?
手掌心

TA贡献1942条经验 获得超3个赞

先说一个最原始的方法实现


class Dispatcher {

    constructor() {

        this._event = [];

    }

    on(eventName, fn) {

        var subscription = {

            eventName,

            callback: fn

        };

        this._event.push(subscription);

        return this;

    }

    off(eventName, fn) {

        this._event = this._event.filter(

            subscription => !(subscription.eventName === eventName && (fn ? subscription.callback === fn : true))

        );

        return this;

    }

    emit(eventName, ...data) {

        this._event.forEach(subscription => {

            if (subscription.eventName === eventName) {

                subscription.callback(...data);

            }

        });

        return this;

    }

}


var leftList = [

    {productId: 10006},

    {productId: 10031},

    {productId: 10016},

    {productId: 10017},

];



var leftList = leftList.map((item, index) => ({...item, order: index,}));


var rightList = [];


var dispatch = new Dispatcher();


dispatch.on('select', function(product) {

    leftList = leftList.filter(_product => product !== _product);

    rightList.push(product);

});


dispatch.on('unselect', function(product) {

    rightList = rightList.filter(_product => product !== _product);

    leftList.push(product);

});


dispatch.emit('select', leftList[0]);

console.log('leftList: ', [...leftList],'\n', 'rightList', [...rightList]);


dispatch.emit('unselect', rightList[0]);

console.log('leftList: ', [...leftList],'\n', 'rightList', [...rightList]);

然后再说一个比较Vue的,左右两列应该算兄弟组件之间的通信,组件的代码和视图的代码应该在两个js文件。组件的通信可以通过子组建1 -> 父组件 -> 子组建2,但是比较麻烦。


我感觉可以用Vuex了。


查看完整回答
反对 回复 2019-04-08
?
德玛西亚99

TA贡献1770条经验 获得超3个赞

请标明右侧以什么顺序排列


查看完整回答
反对 回复 2019-04-08
  • 3 回答
  • 0 关注
  • 526 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号