How to add native events for custom components
Custom components (Components) are one of the important knowledge blocks of vue. Many people will find a question when using them: Why does not bind click events in the component work? Let’s take a look at the reasons here.
Directly binding the native event vue in a custom component is "unliked". It will think that you have not defined this event, so there is no response.
What are native events?
For example, click click, mouseover mouse in, mouseout mouse out, keyup keyboard press and lift, keydown keyboard press and so on, etc. are all native events.So what to do?
. $emit() pass
<body> <div > <Jsxj :jsxj="message" @click="JsxjChange"></Jsxj> </div> </body>
<script> var vm = new Vue({ el:"#app", data:{ message:"Hello World" }, components:{ Jsxj:{ props:['jsxj'], template:`<p @click="pChange">{{jsxj}}</p>`, methods: { pChange(){ this.$emit("click") } }, } }, methods: { JsxjChange(){ ="Hi, Jsxj" } }, }) </script>
The first method is to pass the event through $emit(). For example, code: We set a template in the custom component Jsxj, trigger the native click event on the <p> native element in the template, call the function pChange(), and use $emit() to pass the custom event click upwards. The parent component Jsxj receives this event, so the click can be triggered normally.
. native attributes
<body> <div > <Jsxj :jsxj="message" @="JsxjChange"></Jsxj> </div> </body>
<script> var vm = new Vue({ el:"#app", data:{ message:"Hello World" }, components:{ Jsxj:{ props:['jsxj'], template:`<p>{{jsxj}}</p>` } }, methods: { JsxjChange(){ ="Hi, Jsxj" } }, }) </script>
The second method is relatively simple.
The code is similar, but we no longer use $emit() to pass custom events from the child to the parent, which is too troublesome. Instead, we use the native attribute to help @="JsxjChange", so that the component will know that this is a native event click and call the corresponding function.
vue uses native events
I used the element ui framework in the project. Some components do not have encapsulated events, such as click events. I felt that they did not work when using them. Later, I checked the official vue document and found that some native events are not provided. In addition, our customized components cannot directly use click events. We need to write .native after the click event to take effect
That is, for example:
<el-card @ = "enter"></el-card>
The above is personal experience. I hope you can give you a reference and I hope you can support me more.