Home>Article>Web Front-end> Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)
This article brings you relevant knowledge about Vue3. It mainly introduces how Vue3 implements a global search box. I will share my complete implementation ideas. Let’s take a look. Hope it helps those in need.
Preface: Since learning vue, I have been thinking about the globalcommand Kfunction of the vue official website to call up the global keyword search function. It just so happens that a recent project also needs to implement a global search function, and it just so happens that I can learn the idea of this function with pay. The level of tutorials on the Internet is uneven, and in a previous project, I happened to have done a function similar to global pop-up breadcrumbs, so I drew inferences and wrote a global search box that our project needs, and I would like to share my ideas.
Note: This article will not teach you how to write code right away, but will serve as a guide to guide you step by step to understand the design of this component. ideas. Will explain it from the perspective of"If I am a beginner, if someone can tell me this when I am learning this knowledge, then I can understand it quickly"Professor It is better to teach people how to fish than to teach them how to fish. I hope you can expand your thinking and draw inferences when reading this article.1. File preparation
File
File
File
2. Search box style
Sketch a very simple squaredivin the file and wrap it with aninputtag to quickly proceed with the following learning.But first we need to clarify our thinking. This component will appear at the top of our page, so absolute layout needs to be used inside the component. Let’s go to
SearchBar.vueto set a style for the outermostdiv
. The other styles here are written usingUno CSS
, which is small and unused. Friends don’t need to worry, it’s just a simple style and has nothing to do with the central content of this article. (CSS written as computed properties has no special meaning in this scenario, it is just more consideration during design)3. Rendering function
file prepared previously and import these two fromvuefunction, and introduce the simple version of the search box (SearchBar.vue) written in the previous step into this file.
may be a little more familiar with it, but in that article, it was also my first time I came into contact with these two functions, so the summary at that time was not particularly accurate, so I reorganized my thinking and explain it here.
It can be seen that the first parameter of this function is required and can be astring
andComponent
. This article focuses on the parametersThe case of Component
. The point is that the return value of this function is aVNode
, which you must be familiar with,Virtual Node
. Readers of this article may be familiar with virtualdomThe principle may not be so clear, but I believe you must know its basic mechanism.Vueactually rendersvirtual dom first -->and then converts it into real dom.
Don’t rush to write the code. I think you may know this way of writing better, such as the simple pop-up box we wrote in theSearchBar.vuefile earlier.The style of the entire component is written in the component provided byVue, but you have to know thatVuestill passes Callh()to complete the construction of the virtualdom. And is just syntactic sugar provided byVueto allow you to develop with the familiar nativehtml. (Well, you can understand it this way)
Then we can according to the introduction of theh()function above, the first parameter it receives can beComponent
, then isn’t ourSearchBar.vue
just a component? So if I don’t want to use
to display this component, can I write it like this?h(SearchBar.vue)
. Yes, yes, you can write it like this. Don’t forget that the return value ofh
is theVnodewe want to get, so the correct way to write it is like this.
SearchBar.tsfile.
present, onedismiss.
VNodeand then find a way to process it into a realdom. After the above study, you can immediately think of the following writing method in the first step.
render()function. Now that we have virtual
dom, how can we getreal dom?Vueprovides us with such a function. Here we need to focus on seeing that the type of this function is a value, which is aRootRenderFunctiontype.
renderfunction is acontainer:HostElement, and then Let's open ourmain.tsfile, let's jump into the definition part ofmount,
Did you find the magic place, although we don't knowHostElement What is the type of, but do you know what parameters are filled in yourmountfunction? (If I forgot, I turned around and consciously reviewed the official website.)
Yes, it is the only real
domin the world, a simplediv# with the ID nameapp
## element.Due to space limitations, you can briefly understand here first. Therenderfunction will wrap your virtualdominto a realdomelement. But you need to give it a realshell domto tell it where to render the virtualdom.
ok, after getting a packaged virtual dom, the next step is to tell the browser where to render this element. What we need to think about here is that since it can pop up globally, it needs to pop up on all components.The simplest way is to make it appear in the first element ofbody, then it will be at the same level as all the components of our web page (tips: usually all our page components will be written inbody internalis within adiv. What? You ask me why? Please open yourindex.htmland take a look. Have you forgotten ourApp.vueis hung in this real element withid app)In fact, the idea of our operation is very simple. When I press the global search button , then you can insert my component before the element of Okay, now we can see the basic effect, let’s test it. Let us write a button in the HeresearchBarcan be rendered on the page, but we don’t know how yet Making it disappear is actually very simple. We just need to remove thisdomelement at the right time.We need to know one thing here, we need to promote When I write this, You may have discovered a small problem. When I keep pressing theSearch button, multiple search boxes will appear, but what we hope is that only one search box will appear globally. Thinking about it from another angle, that is, at the same time, only one instance of this In the above case, we can already go in the Open theuseSearch.tsfile we prepared before, and we transform the SearchBar instance that was previously generated globally in Let’s try it out in Before doing this, we need to understand a concept and pay attention to our So if I add a keyboard event to the global At this time, let’s click keydownevents support multiple The keys are pressed simultaneously. What happens when we press the "command" and "K" keys at the same time?But we found that there does not seem to be the attribute We can see that the keyboard eventeventhas akeyattribute, and its value happens to be a string type" k”, Here I will directly publish the writing method. js allows us to judge whether two buttons are pressed at the same time. Let’s test it, let’s goApp.vueRemove these two buttons in the fileThen print it and press it As we can see above, such a sudden appearance There seems to be a little bit of abruptness. I hope that this search box can have a slight panning effect when it appears. (Similar to the effect below) How can I do this? ? I will introduce a simpler idea here. We preset a Then go back to our Then go back to our Note:style, this point is just a class name selector, don’t forget the basics. Test the effect: on the ## of the pop-up box #inputImplementing auto-focusing on the frame is very simple compared to what was mentioned before. I have just gone through it here. Just call thefocusmethod ofinputitself innextTick. dialog,modalbox etc. We need to understand the idea of component library component implementation, rather than just copy and paste. 1. How to save search history? SearchBar.ts vue.js Video Tutorial"App.vue
component, and then call thepresent
method on theSearchBarCreator
instance. (makerdoesn’t feel so reasonable. Later we changedSearchBarMaker
toSeachBarCreator
. Only the name changed, and the logic didn’t change at all. .?)The effect is as follows:searchBar
to the global scope of the current file, not justnew
inopen
.
ok, let’s test it4. Optimize the code logic of the SearchBarCreator constructor
SeachBar
created by usnew
can appear. Think about it?, I add a variable,isShowing is being displayed
, if it is being displayed, then when the user callspresent
again, I will call the instance itselfdismiss
Is it feasible to make it disappear?
Test it:
OK, it seems that the current problem is perfectly solved.5. Write a globally unique calling instance
App.vue
filenew
An example to call this search box. But what if we add that we now need to call this search box in theXXX.vue
file? Do I still need to re-introduce it and thennew
? nonono, a certain boss said that programmers are very lazy and cannot write such low-level repetitive code. So how to achieve itApp.vue
to make it Generate one in a globaltsfile, and then encapsulate some of the methods of this instance itself into functions and expose them to the outside. Then I can call these two methods on this instance anywhere in the world.App.vue
.
This is the calling method of our previousApp.vue
file.Let’s transform it.Let’s test the function again to see if there are any problems
This will be much more convenient. We can call this “only search box” at any location6. Add global shortcut keysCommand K
main.ts
File, who did we hang under the realdom
of the globalid='app'?
Yes, it is theApp.vuecomponent we mentioned earlier.window
object when thisApp.vuecomponent is mounted, right? Is that enough? How to add it? In fact, it is very, very simple. To use the key combination, we need to use"keydown". Why is it not"keypress"? Readers can check the difference between the two by themselves. It is not the main content of this article.command
to see what is printed. The focus here is themetaKey
attribute on the keyboard event.Here we can also deduce that the event of pressing"ctrl"isK:true
, so how can we judge? Don't worry and continue looking down.
command
andk
when.Test it:7. Add the animation that appears
Css
in thestyleof theApp.vuefile. Animation and give it a good name. Called"searchInput"searBar.vue
component and give us the outermost layer of this component Give it a nice name, I’ll call itsearchBarWrapper
.SearchBar.ts
file, which is the file where ourSeachBarCreatorconstructor is placed. (tips: NotuseSearch.ts) Let me explain the idea here. After calling therenderfunction, this component has actually been rendered into a realdomelement, but we have not specified the rendering position for it. Since it is a realdom, then we can get thisSearchBar.vue component
through thedocument.getElementById method (the same as querySelector, the same meaning)
, Next, I only need to add the class name we just preset inApp.vue
before calling thedocument.body.insertBefore
method,searchInput
, the effect we want is perfectly achieved.8. Automatically focus
2. How to provide real-time search associationsThe source code of the file is posted. I hope readers can use it as a reference only and do not want to copy and paste it directly.
import { h, render } from "vue" import SearchBar from "./SearchBar.vue" class SearchBarCreator { container: HTMLElement appElement: HTMLElement | null showing: boolean _dismiss: () => void constructor() { this.container = document.createElement("div") this.showing = false this.appElement = document.body.querySelector("#app") this.present.bind(this) this.dismiss.bind(this) this._dismiss = this.dismiss.bind(this) } present() { if (this.showing) { this.dismiss() } else { const SearchBar = h(h(SearchBar)) render(SearchBar, this.container) const searchBarWrapperDOM = this.container.querySelector("#searchBarWrapper") searchBarWrapperDOM?.classList.add("animate-searchInputAnimation") document.body.insertBefore(this.container, document.body.firstChild) this.showing = true this.appElement?.addEventListener("click", this._dismiss) } } dismiss() { if (this.showing && this.container) { render(null, this.container) document.body.removeChild(this.container) this.showing = false this.appElement?.removeEventListener("click", this._dismiss) } else { console.log("不需要关闭") } } }
Recommended learning: "
The above is the detailed content of Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code). For more information, please follow other related articles on the PHP Chinese website!