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 global command K function 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 square div in the file and wrap it with an input tag 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.vue to set a style for the outermost div
. The other styles here are written using Uno 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 from vue function, 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 a string
and Component
. This article focuses on the parameters The case of Component
. The point is that the return value of this function is a VNode
, which you must be familiar with, Virtual Node
. Readers of this article may be familiar with virtual dom The principle may not be so clear, but I believe you must know its basic mechanism. Vue actually renders virtual 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 the SearchBar.vue file earlier. The style of the entire component is written in the component provided by Vue, but you have to know that Vue still passes Call h() to complete the construction of the virtual dom. And is just syntactic sugar provided by Vue to allow you to develop with the familiar native html. (Well, you can understand it this way)
Then we can according to the introduction of the h() function above, the first parameter it receives can be Component
, then isn’t our SearchBar.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 of h
is the Vnode we want to get, so the correct way to write it is like this.
SearchBar.ts file.
present, one dismiss .
VNode and then find a way to process it into a real dom. 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 get real dom? Vue provides us with such a function. Here we need to focus on seeing that the type of this function is a value, which is a RootRenderFunction type.
render function is a container:HostElement, and then Let's open our main.ts file, let's jump into the definition part of mount,
Did you find the magic place, although we don't know HostElement What is the type of , but do you know what parameters are filled in your mount function? (If I forgot, I turned around and consciously reviewed the official website.)
Yes, it is the only real
dom in the world, a simple div# with the ID name app
## element. Due to space limitations, you can briefly understand here first. The render function will wrap your virtual dom into a real dom element. But you need to give it a real shell dom to tell it where to render the virtual dom.
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 of body, 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 in body internal is within a div. What? You ask me why? Please open your index.html and take a look. Have you forgotten our App.vue is hung in this real element with id 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 <div id="app">. <img src="https://img.php.cn/upload/article/000/000/020/659e9d144b30400682dc69d8bf2b853c-18.png" alt="Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)" loading="lazy"><li><p>Okay, now we can see the basic effect, let’s test it. Let us write a button in the <code>App.vue
component, and then call the present
method on the SearchBarCreator
instance. (maker doesn’t feel so reasonable. Later we changed SearchBarMaker
to SeachBarCreator
. Only the name changed, and the logic didn’t change at all. .?)The effect is as follows:
HeresearchBar can be rendered on the page, but we don’t know how yet Making it disappear is actually very simple. We just need to remove this dom element at the right time. We need to know one thing here, we need to promote searchBar
to the global scope of the current file, not just new
in open
.
ok, let’s test it
When I write this, You may have discovered a small problem. When I keep pressing the Search 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 SeachBar
created by us new
can appear. Think about it?, I add a variable, isShowing is being displayed
, if it is being displayed, then when the user calls present
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.
In the above case, we can already go in the App.vue
file new
An example to call this search box. But what if we add that we now need to call this search box in the XXX.vue
file? Do I still need to re-introduce it and then new
? nonono, a certain boss said that programmers are very lazy and cannot write such low-level repetitive code. So how to achieve it
Open the useSearch.ts file we prepared before, and we transform the SearchBar instance that was previously generated globally in App.vue
to make it Generate one in a global ts file, 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.
Let’s try it out in App.vue
.
This is the calling method of our previous App.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 location
Before doing this, we need to understand a concept and pay attention to our main.ts
File, who did we hang under the real dom
of the global id='app'?
Yes, it is the App.vue component we mentioned earlier.
So if I add a keyboard event to the global window
object when this App.vue component 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.
At this time, let’s click command
to see what is printed. The focus here is the metaKey
attribute on the keyboard event. Here we can also deduce that the event of pressing "ctrl" is
keydown events 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 K:true
, so how can we judge? Don't worry and continue looking down.
We can see that the keyboard event event has a key attribute, 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 go App.vue Remove these two buttons in the file Then print it and press it command
and k
when. Test 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 Css
in the style of the App.vue file. Animation and give it a good name. Called "searchInput"
Then go back to our searBar.vue
component and give us the outermost layer of this component Give it a nice name, I’ll call it searchBarWrapper
.
Then go back to our SearchBar.ts
file, which is the file where our SeachBarCreator constructor is placed. (tips: Not useSearch.ts)
Let me explain the idea here. After calling the render function, this component has actually been rendered into a real dom element, but we have not specified the rendering position for it. Since it is a real dom, then we can get this SearchBar.vue component
through the document.getElementById method (the same as querySelector, the same meaning)
, Next, I only need to add the class name we just preset in App.vue
before calling the document.body.insertBefore
method, searchInput
, the effect we want is perfectly achieved.
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 #input Implementing auto-focusing on the frame is very simple compared to what was mentioned before. I have just gone through it here. Just call the focus method of input itself in nextTick.
dialog, modal box etc. We need to understand the idea of component library component implementation, rather than just copy and paste.
There are many areas where this search box can be optimized, and you can bring your own thoughts into it. For example1. How to save search history?
2. How to provide real-time search associations
SearchBar.ts The 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("不需要关闭") } } }
vue.js Video Tutorial"
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!