Home  >  Q&A  >  body text

javascript - The child component triggers a custom event of the parent component, but the parent component does not respond.

The following are sub-components @change='showChange' is the sub-component event
The following templates are registered as order-type components

<template>
<select name="dType" class="form-control" v-el:select @change='showChange'>
      <option value="" v-if="type=='selectAll'">全部</option>
      <option v-for="branch in branchList" :value="branch.id" track-by="$index">
        {{branch.name}}
      </option>
  </select>
</template>

The following are sub-component methods:

        showChange(event) {
            for (let branch of this.branchList) {
                if (branch['id'] === event.target.value) {
                    this.$emit('showChange',branch['prefix']);
                }
            }

The following is the parent component

<order-type @showChange='alert(2)'></order-type>        

But alert(2) is not executed

大家讲道理大家讲道理2663 days ago966

reply all(3)I'll reply

  • 女神的闺蜜爱上我

    女神的闺蜜爱上我2017-07-05 11:05:26

    There is something wrong with you just writing it like this
    It should be

    <order-type @showChange='alertFun'></order-type>     
    父组件有一个方法
    methods: {
        alertFun () {
            alert(2)
        }
    }

    What should be passed here is a function name of the parent component method instead of writing alert(2) directly

    reply
    0
  • 女神的闺蜜爱上我

    女神的闺蜜爱上我2017-07-05 11:05:26

    This should be the problem
    <option v-for="branch in branchList" :value="branch.id" track-by="$index">
    The for in object loop obtains the index, not value, so branch.id cannot be obtained, it can be changed to for of

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-07-05 11:05:26

    The following is a sub-component @change='showChange' is a sub-component event
    The following template is registered as an order-type component

    <template>
    <select name="dType" class="form-control" v-el:select @change:parentChage='showChange'>

      <option value="" v-if="type=='selectAll'">全部</option>
      <option v-for="branch in branchList" :value="branch.id" track-by="$index">
        {{branch.name}}
      </option>

    </select>
    </template>

    The following are sub-component methods:

        showChange(event) {
            for (let branch of this.branchList) {
                if (branch['id'] === event.target.value) {
     /注意此行的修改/               this.$emit('parentChage',branch['prefix']);
                }
            }
            
            
            
    以下是父组件
    <order-type @showChange='alert(2)'></order-type>        
            
     但alert(2) 并未执行 

    reply
    0
  • Cancelreply