首页 文章

无法从Vuejs中的子组件向父组件发出事件

提问于
浏览
0

我的父组件从api获取数据,这是一个字符串数组,然后将其传递给子组件 . 在子组件中,我将父项中的数据显示为下拉列表,当我从下拉列表中选择特定项时,我希望它设置一个特定的变量 . 我已经使用了$ emit和$ event,如文档中所示,但它无法正常工作 . 请查看我的代码并告诉我哪里出错了 .

父组件App.vue

<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 .

1 回答

  • 0

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

    将您的代码更改为类似于使用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>
    

    查看演示link

相关问题