如何使用Vue捕获事件目标(event.target)?

huangapple go评论55阅读模式
英文:

How to catch an emeit event.target with vue?

问题

如何使用Vue捕获一个$emit事件目标?尝试创建一个$emit的Vue并出现错误。

我尝试捕获来自子组件的事件目标发射,通过将输入字符串的onChange作为参数传递。但是出现了一个错误"Cannot read properties of undefined (reading 'target')"。尽管语法是正确的,我认为。

链接:https://stackblitz.com/edit/nuxt-bootstrap-vue-dynamic-img-iiam9a?file=components%2FBrand.vue,components%2FMoneyAmount.vue,pages%2Findex.vue,components%2FCategory.vue,components%2FRating.vue,components%2FSearch.vue,components%2FProductList.vue,store%2Findex.js,components%2FProduct.vue

<input
  type="text"
  placeholder="在这里搜索"
  v-model="search"
  :change="$emit('search', $event.target.value)"
/>

<!-- 父组件 -->

<Search @search="searchProduct" />

<script>
methods: {
    searchProduct(searchInput) {
      this.search = searchInput;
    },
  },
</script>
英文:

How to catch an emeit event.target with vue ? Trying to make an $emit vue and getting an error

I tryed to catch an event target emit from a child component from an input , passing as a param the onChange input string. But getting an error "Cannot read properties of undefined (reading 'target')". Even though the syntaxis is correct I assume.

https://stackblitz.com/edit/nuxt-bootstrap-vue-dynamic-img-iiam9a?file=components%2FBrand.vue,components%2FMoneyAmount.vue,pages%2Findex.vue,components%2FCategory.vue,components%2FRating.vue,components%2FSearch.vue,components%2FProductList.vue,store%2Findex.js,components%2FProduct.vue

&lt;input
      type=&quot;text&quot;
      placeholder=&quot;Search here&quot;
      v-model=&quot;search&quot;
      :change=&quot;$emit(&#39;search&#39;, $event.target.value)&quot;

// Parent

  &lt;Search @search=&quot;searchProduct&quot; /&gt;

&lt;script&gt;
methods: {
    searchProduct(searchInput) {
      this.search = searchInput;
    },
  },
    /&gt;

答案1

得分: 2

在Vue中监听事件,我们使用 v-on:event-name=&quot;...&quot; 语法。也可以缩写为 @event-name=&quot;...&quot;。您可以在这里找到更多详情。

您错误地监听了 :change 而不是 @change。所以更新的代码应该是:

<input
  ...
  @change=&quot;$emit(&#39;search&#39;, $event.target.value)&quot;
  |__ 使用 `@` 代替 `:`
/>
英文:

To listen for events in Vue, we use v-on:event-name=&quot;...&quot; syntax. It can also be shortened to @event-name=&quot;...&quot;. You can find more details here.

You are mistakenly listening for :change instead of @change. So update code should be:

&lt;input
  ...
  @change=&quot;$emit(&#39;search&#39;, $event.target.value)&quot;
  |__ `@` instead of `:`
/&gt;

huangapple
  • 本文由 发表于 2023年5月29日 21:10:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76357669.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定