Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vue.js/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 侦听自定义事件,但在组件外部设置代码';s HTML_Javascript_Vue.js - Fatal编程技术网

Javascript 侦听自定义事件,但在组件外部设置代码';s HTML

Javascript 侦听自定义事件,但在组件外部设置代码';s HTML,javascript,vue.js,Javascript,Vue.js,因此,我正在在线阅读文档,唯一可以声明“自定义事件”的方法如下: <my-component v-on:my-event="doSomething"></my-component> this.$emit("doSomething", "a string value") ; export default { name: testComponent, created(){ this.$o

因此,我正在在线阅读文档,唯一可以声明“自定义事件”的方法如下:

<my-component v-on:my-event="doSomething"></my-component>
 this.$emit("doSomething", "a string value") ;
export default {
   name: testComponent,
   created(){
      this.$on("mycustomevent", this.customevent);
   },
  methods:{
    customevent(){
      alert("this is a custom event");
    }
  }  
}

现在,我不认为在
标记之外,没有其他方法可以声明事件,比如在
导出默认值
对象上?因为如果我正在收听大量事件,那么使用
标记将非常不舒服。

您应该发出事件的名称。在本例中,
this.$emit(“我的事件”、“字符串值”)

对于希望以编程方式将事件添加到父组件的灵魂,您可以这样添加它:

<my-component v-on:my-event="doSomething"></my-component>
 this.$emit("doSomething", "a string value") ;
export default {
   name: testComponent,
   created(){
      this.$on("mycustomevent", this.customevent);
   },
  methods:{
    customevent(){
      alert("this is a custom event");
    }
  }  
}
然后在子组件上,您可以像这样调用事件(例如使用:mounted())

这对于动态布局包装器组件非常有用,因为在我的示例中,您无法在App.vue上为自定义主题声明自定义事件:

<template>
  <div id="app">    
      <component :is="layout">
          <router-view :layout.sync="layout"/>
      </component>
  </div>
</template>

依赖于变量且必须适用于所有模板或视图(在我的布局示例中)
现在,您可以在js代码中启动自定义事件,而无需在js中声明它们

这是为了调用它,但是我想在组件的导出默认{}初始化中声明v-on,这是可能的吗?我认为这是不可能的。但是如果你正在处理大量的活动,我建议你尝试一下像这样的酒吧/分馆