Vue triggers a method in a sibling component

Requirement: There are two sibling components on the page. If I click the button in component 1, I need to trigger a method in component 2;

Here, take the shopping cart page as an example: I select the selected status of a certain product in the product list, and in the settlement component, determine the all-selected status based on whether there is an unselected status in the list.

Effect:

Step 1: Introduce two sibling components to the parent page

<!-- 商品列表组件 -->
<cartGoodsList></cartGoodsList>
<!-- 结算组件 -->
<carSbumit></carSbumit>

Step 2: Add events to the product selection box in the list component

methods: {
        checkItem(e){//选中/或取消选中某个商品,进而判断全选的状态方法
            
            //实现思路:需要调用结算组件中统计列表是否有未选中状态,从而判断全选的状态
            //1、点击某个商品选中或未选中时,触发一个方法传递到父组件中,并传递当前的选中状态
            //2、在父组件中给结算组件定义ref属性
            //3、在父组件接收在此组件中定义的itemGoodsTypeFn方法
            //4、在itemGoodsTypeFn这个方法中触发兄弟组件ref属性,去触发他里面的方法
            //5、在结算组件中循环列表,判断其中如果有未选中状态的话,直接将状态更改为false,并跳出循环
            this.$emit('itemGoodsTypeFn',e)
        }
    },

Step 3: Receive the method of the list component on the parent component page, and add the ref attribute to the settlement component

<!-- 购物车列表组件,并传参 -->
<!-- itemGoodsTypeFn方法是子组件传递过来的,要根据这个方法触发兄弟组件carSbumit -->
<cartGoodsList :list="list" @itemGoodsTypeFn="cartListCheckType"></cartGoodsList>
<!-- 结算组件 -->
<carSbumit ref="checkAllType"></carSbumit>

Step 5: Use the method received from the list component to trigger the method in the settlement component

cartListCheckType(e){
//这是列表组件在触发选中或未选中时,向父组件传递的方法,通过这个方法去触发兄弟组件里面的方法
    this.$refs.checkAllType.inspectCheckAll()
}

Step 6: Determine the full selection status based on the current product selection status in the settlement component.

<!--全选按钮-->

<van-checkbox v-model="checked" @click="checkedAll">全选</van-checkbox>
computed:{
    ...mapState('cart',['list']),//这是列表的值,我的值存在store中
},
//全选按钮的默认值
data() {
        return {
            checked:false
        };
    },
methods: {
    inspectCheckAll(){//检查商品列表中是否都是选中状态
        let chek = false
        let listArr = this.list
        for(var i=0;i<listArr.length;i++){//循环列表,判断如果有未选中的直接将状态改成false直接跳出循环
                if(!listArr[i].check){
                    chek=false
                    break;
                }else{
                    chek=true
                }
            }
            this.checked=chek//最终赋值状态
        }
},

At this point, you have completed judging the all-selected state based on the current selected state. Click Select All to select or unselect the list. If it is not listed in it, there are other simpler methods. Here is just one.

Guess you like

Origin blog.csdn.net/qq_17211063/article/details/131978559