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

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

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

  1. <input
  2. type="text"
  3. placeholder="在这里搜索"
  4. v-model="search"
  5. :change="$emit('search', $event.target.value)"
  6. />
  7. <!-- 父组件 -->
  8. <Search @search="searchProduct" />
  9. <script>
  10. methods: {
  11. searchProduct(searchInput) {
  12. this.search = searchInput;
  13. },
  14. },
  15. </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

  1. &lt;input
  2. type=&quot;text&quot;
  3. placeholder=&quot;Search here&quot;
  4. v-model=&quot;search&quot;
  5. :change=&quot;$emit(&#39;search&#39;, $event.target.value)&quot;
  6. // Parent
  7. &lt;Search @search=&quot;searchProduct&quot; /&gt;
  8. &lt;script&gt;
  9. methods: {
  10. searchProduct(searchInput) {
  11. this.search = searchInput;
  12. },
  13. },
  14. /&gt;

答案1

得分: 2

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

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

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

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:

  1. &lt;input
  2. ...
  3. @change=&quot;$emit(&#39;search&#39;, $event.target.value)&quot;
  4. |__ `@` instead of `:`
  5. /&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:

确定