First, recently in the work process to achieve a fuzzy match search function, taking into reusable components, it alone out of the search box as a sub-assembly. In the past development, I usually emit in the input box to change the value of a parent component event and bring some parameters parent components required (such as keyword search, or search results returned after)
Probably the implementation of the following:
父组件 <template> <div> <search @test="getData"></search> <button @click="submit">提交</button> </div> </template> <script> import search from '@/components/index/search.vue' export default { data() { return { keywords: '' } }, components: { search }, methods: { getData(val){ this.keywords = val }, submit() { console.log('keywords:', this.keywords) } } } </script> 子组件 <template> <div> <input @input="inputChange" type="text" name="keywords"> </div> </template> <script> export default { props: ['keywords'], methods: { inputChange(e) { this.$emit('test', e.target.value) } } } </script>
Second, this time in the realization of the time, I remember vaguely mentioned when looking at Vue api before, to add the component v-model, wanted to try it this way, I understand that according to the official website explained:
v-model this way binding equivalent of doing two operations: (1) This component added to the current value of a property (2) This component is bound to present an input event; thus I modified implementation as follows:
Parent component:
<template> <div> <search v-model="keywords"></search> <button @click="submit">提交</button> </div> </template> <script> import search from '@/components/index/search.vue' export default { data() { return { keywords: '' } }, components: { search }, methods: { submit() { console.log('keywords:', this.keywords) } } } </script>
Subassembly:
<template> <div> <input :value="value" @input="$emit('input', $event.target.value)" type="text" name="keywords"> </div> </template> <script> export default { props: ['value'] } </script>
Third, the summary: In fact, two ideas are the same, all sub-components emit events by parent component values to pass, but in the form of v-model is more intuitive and simple -