1. Understand the translation function
I believe everyone is familiar with the translation software. Usually, the web version is to enter English into the given left text box, and after a short while the text box on the right will give a Chinese translation.
To implement this translation function, we will not consider how the backend performs the translation business, but only consider the front-end design.
Design plan:
① It can be that after the user enters English, assuming that the user has no input in 0.5s, the text box on the right will automatically display the translated results.
② When the user enters English, he needs to press Enter or click the translation button, and the text box on the right will display the translated results.
Solution ② is easier to implement, it is nothing more than clicking the button and submitting a request to the backend translation, which is OK. Solution ① is equivalent to capturing the user's behavior and automatically submitting a request to the backend translation. Here we need to use the watch listener in Vue explained in this issue!
2. Watch listener (monitor) syntax
First of all, you need to understand the role of watch:
Monitor data changes, perform some business logic or asynchronous operations
The syntax is as follows:
- Watch is also declared in configuration items of the same level as data
- Simple writing method: Direct monitoring of simple type data
- Complete writing: Add additional configuration items
data: { words: 'hello', obj: { words: 'cat' } }, watch: { // This method will trigger execution when the data changes words (newValue, oldValue) { // code ... some business logic or asynchronous operations. }, '' (newValue, oldValue) { // code ... some business logic or asynchronous operations. } }
Simply put, it is to configure the data name or object to be monitored in the watch configuration item. Once the content of the monitored object changes, the corresponding code block in the configuration item will be immediately executed.
With the above simple understanding, we will simulate and implement a translation function to experience the listener more intuitively.
3. Simulate and implement translation functions
Let’s look at the code directly here, focusing on the final running results and the code part in js.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; font-size: 18px; } #app { padding: 10px 20px; } .query { margin: 10px 0; } .box { display: flex; } textarea { width: 300px; height: 160px; font-size: 18px; border: 1px solid #dedede; outline: none; resize: none; padding: 10px; } textarea:hover { border: 1px solid #1589f5; } .transbox { width: 300px; height: 160px; background-color: #f0f0f0; padding: 10px; border: none; } .tip-box { width: 300px; height: 25px; line-height: 25px; display: flex; } .tip-box span { flex: 1; text-align: center; } .query span { font-size: 18px; } .input-wrap { position: relative; } .input-wrap span { position: absolute; right: 15px; bottom: 15px; font-size: 12px; } .input-wrap i { font-size: 20px; font-style: normal; } </style> </head> <body> <div > <!-- Conditional selection box --> <div class="query"> <span>Translated into languages:</span> <select> <option value="italy">Italy</option> <option value="english">English</option> <option value="german">German</option> </select> </div> <!-- Translation box --> <div class="box"> <div class="input-wrap"> <textarea v-model=""></textarea> <span><i>⌨️</i>Document Translation</span> </div> <div class="output-wrap"> <div class="transbox">{{ result }}</div> </div> </div> </div> <script src="/npm/vue@2/dist/"></script> <script> const getRandomCharacter = () => { const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const randomIndex = (() * ); return characters[randomIndex]; } const getRandomEnglishString = (length) => { let randomString = ''; for (let i = 0; i < length; i++) { randomString += getRandomCharacter(); } return randomString; } const app = new Vue({ el: '#app', data: { obj: { words: '' }, result: '', // Translation results timer: null // Delayer }, watch: { // This method will be executed when the data changes // newValue new value, oldValue old value (usually not used) '' (newValue) { // Anti-shake: Delay execution → Wait for a while before doing something, and it will be executed if it is not triggered again for a period of time. clearTimeout() = setTimeout(() => { = getRandomEnglishString(10) // Randomly generate strings of length 10 }, 300) } } }) </script> </body> </html>
The function of the above code is that if you enter it casually, if you don’t enter it for 300 milliseconds, the only thing in the result will be automatically updated. From the code level, when the value of this variable changes, the code of the corresponding code block will be immediately triggered.
I may have a little doubt when I see this. Can't I listen directly to the entire obj object? Of course, but deep monitoring is required here!
That is, the complete writing method of watch that will be discussed later.
4. In-depth monitoring of watch
This is the true completeness of the watch.
Complete writing —> Add additional configuration items
- deep:true deep monitoring of complex types
- immediate:true Initialization Execute once immediately
data: { obj: { words: 'hello', lang: 'italy' }, }, watch: {// watch full writing method obj: { deep: true, // In-depth monitoring immdiate:true,//Execute the handler function immediately handler (newValue) { (newValue) } } }
In-depth monitoring, that is, any words or lang attributes in the obj object change, will immediately execute the handler function!
The above simulation implementation of the translation code has a small hole. When switching languages, the translation effect will not be triggered. At this time, you can use deep monitoring of the entire obj object to achieve it. Go and optimize it quickly!
This is the article about Vue using watch listener simulation to implement translation functions. For more related content related to Vue watch simulation, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!