


Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)
Jan 13, 2023 pm 04:22 PMThis 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.
How to implement a global search box in Vue3
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
You need to prepare three files in the early stage to complete this global search box
- SearchBar.ts
File
- SearchBar.vue
File
- useSearch.ts
File
2. Search box style
Style issues are not the focus of this article, you can spend five minutes on
SearchBar.vueSketch 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
andrender Function (Key Point)
- Open the
- SearchBar.ts
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.
Readers who have read my previous article - Vue3 implements a Toast
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.
First of all, let’s take a look at the definition of this function from the introduction on the official website. It can be seen that the first parameter of this function is required and can be a
string
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 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 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 the Vnode we want to get, so the correct way to write it is like this.
SearchBarMaker constructor and present method
- Let’s Go back to the
SearchBar.ts
file.
- First think about it, this search box must have a function that appears and a function that disappears?, ok, give a name, one
present, one dismiss .
- Next I need to create a
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.
- #The following one is even more important,
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 RootRenderFunctiontype.
- Here we change our thinking and look at the second parameter of the
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 nameapp
## element. Due to space limitations, you can briefly understand here first. The renderfunction 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="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/020/659e9d144b30400682dc69d8bf2b853c-18.png" class="lazy" 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 thepresent
method on theSearchBarCreator
instance. (maker doesn’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:
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 justnew
inopen
.ok, let’s test it
In the above case, we can already go in the
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 itOpen 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 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 locationBefore doing this, we need to understand a concept and pay attention to our
main.ts
File, who did we hang under the realdom
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 themetaKey
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”,
Let’s test it, let’s go App.vue Remove these two buttons in the file
Then print it and press it
command
andk
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 itsearchBarWrapper
.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 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.Note: style, this point is just a class name selector, don’t forget the basics.
Test the effect:
4. Optimize the code logic of the SearchBarCreator constructor
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.
5. Write a globally unique calling instance
6. Add global shortcut keysCommand K
Here I will directly publish the writing method. js allows us to judge whether two buttons are pressed at the same time.
7. Add the animation that appears
8. Automatically focus
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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

vue3+vite: How to solve the error when using require to dynamically import images in src

How Vue3 parses markdown and implements code highlighting

How to refresh partial content of the page in Vue3

How to solve the problem that after the vue3 project is packaged and published to the server, the access page displays blank

How to select an avatar and crop it in Vue3

How to use Vue3 and Element Plus to implement automatic import
