Home > Web Front-end > JS Tutorial > body text

How to pass events in vue components

亚连
Release: 2018-06-14 15:44:38
Original
2958 people have browsed it

My recent work requires the use of vue, so the one I have been exposed to the most recently is vue. Now I will introduce to you the event transfer between vue components. Friends who need it can refer to it

Since the new work requires the use of vue, So the one I have been exposed to the most recently is Vue. Because I have been using react before, I got started with Vue very quickly.

I also try to find some similarities and differences between the two of them. In addition to some more auxiliary methods, the biggest difference should be that for communication between components, there are not only props, but also event monitoring, which is Can be passed between components.

However, in vue2., vue introduced the diff algorithm and virtual dom to improve efficiency. We know these things. In order to deal with frequent updates of DOM elements, we propose an optimization solution. Are there conflicts between frequent changes, updates, and initialization of event listeners? When components need to be changed, are registered events unbound? ? Let's write some simple code to verify it.

We write two buttons made by p, one is written in html code, and the other is inserted in the form of a component. The two buttons are exactly the same, but we add a disabled attribute to the outer layer and pass if- else to determine disabled and display different buttons (of course we would not write code like this in normal scenarios, here we just simulate a special scenario in this way, and we will consider whether this scenario exists in our business).

<template>
 <p class="test">
 <p class="btn" v-if="disabled" @click="handleClick">可点击</p>
 <p class="btn" v-else >不可点击</p>
 <Button v-if="disabled" @clickTest="handleClick">可点击</Button>
 <Button v-else>不可点击</Button>
 </p>
</template>

<script>
import Button from &#39;./Button&#39;
export default {
 data () {
 return {
  disabled: true
 }
 },
 methods: {
 handleClick() {
  alert(&#39;可点击&#39;)
 }
 },
 components: {
 Button,
 },
 mounted() {
 setTimeout(() => {
  this.disabled = false
 }, 1000)
 }
}
</script>
<style>
.btn{
 margin: 100px auto;
 width: 200px;
 line-height: 50px;
 border: 1px solid #42b983;
 border-radius: 5px;
 color: #42b983;
}
</style>
Copy after login

We add a little style to make it look as good as possible. It looks very simple. Two buttons are bound to a click event when they are clickable, and not bound to them when they are not clickable. The difference is that one is directly written html code, and the other is a component. The code of the component is as follows:

<template>
 <p class="btn" @click="handleClick"><slot></slot></p>
</template>
<script>
 export default {
  methods: {
   handleClick() {
    this.$emit(&#39;clickTest&#39;)
   }
  }
 }
</script>
Copy after login

Then add a 1 second settimeout to the mounted period to change disabled to false, and then let’s test it

When disabled is still true, a clickable alert will pop up when clicking both buttons. But when disebled changes to false, the one written in HTML will no longer pop up, but the one written in components below will still pop up.

It is very difficult to locate this kind of problem when it occurs, because the code obviously will not call this clicktest event, and on the page, we can also determine The button has become unclickable. So why is this event still being called?

Let’s start with the diff algorithm. The algorithm complexity of the traditional diff tree algorithm is O(n^3). When react introduced the diff algorithm, it eliminated the cross-level movement, that is, only Comparing the similarities and differences of nodes at the same level reduces the algorithm complexity to O(n), allowing us to frequently refresh the entire page unscrupulously (but in moderation, of course).

(Haha, no picture)

Diff has a strategy that two components with the same class will generate similar tree structures, and two components with different classes will generate different tree structure. So its comparison order is

1) tree diff

2) component diff

3) element diff

Back to our code, When we perform component diff, we think they are the same components, and then perform element diff, that is, add, delete and move. So the problem occurs here. When instantiating the component, we initialize the event listener, but when replacing the same component When entering the DOM in the component, Vue did not delete the event listener that has been added to the component.

Let’s take a look at the vue code.

Vue.prototype.$emit = function (event: string): Component {
 const vm: Component = this
 if (process.env.NODE_ENV !== &#39;production&#39;) {
  const lowerCaseEvent = event.toLowerCase()
  if (lowerCaseEvent !== event && vm._events[lowerCaseEvent]) {
  tip(
   `Event "${lowerCaseEvent}" is emitted in component ` +
   `${formatComponentName(vm)} but the handler is registered for "${event}". ` +
   `Note that HTML attributes are case-insensitive and you cannot use ` +
   `v-on to listen to camelCase events when using in-DOM templates. ` +
   `You should probably use "${hyphenate(event)}" instead of "${event}".`
  )
  }
 }
 let cbs = vm._events[event]
 if (cbs) {
  cbs = cbs.length > 1 ? toArray(cbs) : cbs
  const args = toArray(arguments, 1)
  for (let i = 0, l = cbs.length; i < l; i++) {
  try {
   cbs[i].apply(vm, args)
  } catch (e) {
   handleError(e, vm, `event handler for "${event}"`)
  }
  }
 }
 return vm
 }
Copy after login

Vue determines whether there are bound events through the _events attribute in vdom. Let's take a look at the _events

:
clickTest
:
Array(1)
0
:
ƒ invoker()
length
:
Copy after login

of the unclickable button and find that the clicktest is still there. That's the problem.

So how should we avoid such a problem? Should we solve the problem through diff comparison or look at the code.

function sameVnode (a, b) {
 return (
 a.key === b.key && (
  (
  a.tag === b.tag &&
  a.isComment === b.isComment &&
  isDef(a.data) === isDef(b.data) &&
  sameInputType(a, b)
  ) || (
  isTrue(a.isAsyncPlaceholder) &&
  a.asyncFactory === b.asyncFactory &&
  isUndef(b.asyncFactory.error)
  )
 )
 )
}
Copy after login

That is to say, for diff, the so-called same first determination principle is key.

Key is also an attribute added when react introduced diff. It is used to determine whether the front and rear vdom trees are unified elements (note that it is a sibling relationship), so we only need to add key to the code to avoid This problem

<Button key="1" v-if="disabled" @clickTest="handleClick">可点击</Button>
<Button key="2" v-else>不可点击</Button>
Copy after login

In this way, when we click the button, the pop-up box will no longer pop up.

Key has a wide range of functions. When we traverse the array to generate dom, adding a determinable unique id (note that array index should not be used) will optimize our comparison efficiency and require fewer dom operations. . We will also add a key to a p to ensure that it will not be re-rendered due to changes in sibling elements (this type of p is usually bound to events or actions other than react or vue, such as generating a canvas, etc.).

So besides adding this unnecessary key value to the component, is there any other way to solve it?

Yes, there is a very anti-Vue but react-like method, which is to pass the callback event through props, like this,

<Button v-if="disabled" :clickTest="handleClick">可点击</Button>
<Button v-else>不可点击</Button>
  props: {
   &#39;clickTest&#39;: {
    type: Function
   }
  },
  methods: {
   handleClick() {
    //this.$emit(&#39;clickTest&#39;)
    this.clickTest && this.clickTest()
   }
  }
Copy after login

虽然vue给了我们更方便的事件传递的方式,但props里是允许我们去传递任何类型的,我的期望是在真实的dom上或者在公共组件的入口处以外的地方,都是通过props的方式来传递结果的。虽然这种方式很不vue,而且也享受不到v-on给我们带来的遍历,但是这样确实可以减少不必要的麻烦。

当然既然用了vue,更好的利用vue给我们带来的便利也很重要,所以对于这种很少会出现的麻烦,我们有一个预期,并可以快速定位并修复问题,就可以了。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

在vue中如何通过v-for处理数组

使用vue如何实现收藏夹

在node.js中有关npm和webpack配置方法

如何通过js将当前时间格式化?

使用vue引入css,less相关问题

The above is the detailed content of How to pass events in vue components. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template