【问题标题】:VueJS 2 - How to Pass Parameters Using $emitVueJS 2 - 如何使用 $emit 传递参数
【发布时间】:2023-03-09 06:22:01
【问题描述】:

我正在使用 VueJS 2 开发一个模态组件。现在,它基本上可以工作了——我点击一个按钮,模态就会打开,等等。

我现在要做的是为模式创建一个唯一的名称,并将按钮与该特定按钮相关联。

这就是我的想法。 modal 有一个唯一的 name 属性:

<modal name='myName'>CONTENT</modal>

这将是关联按钮:

<button @click="showModal('myName')"></button>

我需要弄清楚的是如何将showModal的参数传递给模态组件。

这是我在根 vue 实例中使用的方法(即不在我的模态组件中):

methods: {
    showModal(name) { this.bus.$emit('showModal'); },
}

我想做的是访问组件中的 name 属性——像这样:

created() {
    this.bus.$on('showModal', () => alert(this.name));
}

但这显示为undefined

那么我做错了什么?如何访问模态组件中的 name 属性?

注意:如果您想知道 this.bus.$on 是什么,请参阅我之前提出的问题的以下答案:https://stackoverflow.com/a/42983494/7477670

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component


    【解决方案1】:

    将其作为参数传递给$emit

    methods: {
        showModal(name) { this.bus.$emit('showModal', name); },
    }
    
    created() {
        this.bus.$on('showModal', (name) => alert(name));
    }
    

    另外,如果你想给 modal 一个名字,你需要接受它作为 modal 组件中的一个 prop。

    Vue.component("modal",{
        props:["name"],
        ...
    })
    

    那么我假设你会想做类似的事情,

    if (name == this.name)
        //show the modal
    

    【讨论】:

      【解决方案2】:
      <!-- File name is dataTable.vue -->
      <template>
        <div>
           <insertForm v-on:emitForm="close"></insertForm>
        </div>
      </template>
      
      
      <script>
      
      import InsertForm from "./insertForm";
      
      import Axios from "axios";
      
      export default {
        components: {
          InsertForm
        },
      
        data: () => ({    
        }),
      
        methods: {
          
          close(res) {
            console.log('res = ', res);    
          }
        }
      };
      </script>
      
      <!-- File name is insertForm.vue -->
      <template>
        <div>
          <v-btn @click.native="sendPrameter">
            <v-icon>save</v-icon>
          </v-btn>
        </div>
      </template>
      
      <script>
      export default {
        data: () => ({
         mesage:{
          msg:"Saved successfully",
          color:'red',
          status:1
        }
      }), 
      
        methods: {
          sendPrameter: function() {      
            this.$emit("emitForm", this.mesage);
          }
        }
      };
      </script>
      
      https://vuejs.org/v2/guide/components-custom-events.html
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-10
        • 1970-01-01
        • 2018-02-05
        • 2017-10-24
        • 2018-04-14
        • 2019-09-22
        相关资源
        最近更新 更多