繁体   English   中英

无法从Vue.js的子组件向父组件发出事件

[英]Not able to emit an event to a parent component from child component in Vuejs

我的父组件从api中获取数据,该数据是字符串数组,然后将其传递给子组件。 在子组件中,我将来自父组件的数据显示为下拉列表,当我从下拉列表中选择特定项目时,我希望它设置特定变量。 我已经使用了$ emit和$ event,如文档所示,但是它不起作用。请查看我的代码并告诉我我要去哪里了。

父组件应用程序

<template>
    <div id="app">
        <nlp-vision-catalog v-bind:cataloglist="catalogs"  v-on:listenClick="setcatalogselected($event)" ></nlp-vision-catalog>
    </div>
</template>

<script>
    import NlpVisionCatalog from './components/NlpVisionCatalog'
    import axios from 'axios'

    export default {
        name: 'App',
        components: {
            NlpVisionCatalog
        },
        data (){
            return {
            catalogs :[],
            catalog_selected : ""
        }
    },
    methods:{
        fetchcatalogs(){
                axios.get("http://localhost:5000/clients")
                .then((resp)=>{this.catalogs.push.apply(this.catalogs,
                   resp.data.response.results.client_name);
                }).catch((err)=>{
                    console.log(err);
                })
        },
        setcatalogselected(catalog){
        this.catalog_selected = catalog;
    )}
},
    created(){
        this.fetchcatalogs()
    }
}
</script>
<style></style>

我的孩子组件是NlpVisionCatalog.vue

enter code here
<template>
<div>
    <h3>Select Catalog</h3>
    <select>
        <option v-for="item in cataloglist">
            <p v-on:click="emitbackthecatalog(item)"> {{ item }} </p>
        </option>
    </select>
</div>
</template>

<script>
export default{
    name : 'NlpVisionCatalog',
    props: ['cataloglist'],
    data (){
        return {
            comp: ""
        }
    },
    methods:{
        emitbackthecatalog(catalog_name){
            this.$emit('listenClick',catalog_name);
        }
    }
};
</script>

<style>
</style>

我到底哪里出问题了? ps- http:// localhost:5000 / clients是在我的系统上运行的api。

问题出在您的子组件选择元素中

更改您的代码,使其类似于select元素中的onChange函数

 <h3>Select Catalog</h3>
    <select v-model="selected" v-on:change="emitbackthecatalog(selected)">
        <option v-for="item in cataloglist" :value="item" :key="item" >
           {{ item }}
        </option>
    </select>



data (){
    return {
        selected: ""
    }
  },
  methods:{
    emitbackthecatalog(catalog_name){
        this.$emit('listenclick',catalog_name);
    }
  }

在您的父组件中

<nlp-vision-catalog v-bind:cataloglist="catalogs"  v-on:listenclick="setcatalogselected($event)" ></nlp-vision-catalog>

检查演示链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM