Share 5 little knowledge about Vue, hope it will be helpful to you (4)

9e331b7108c3bac2e18907217e098f30.jpeg

Hello everyone, today I will continue to share 5 little knowledge about Vue, I hope it will be helpful to you.

previous articles

Share 5 little knowledge about Vue, hope it will be helpful to you (1)

Share 5 little knowledge about Vue, hope it will be helpful to you (2)

Share 5 little knowledge about Vue, hope it will be helpful to you (3)

1. How to use Emmit Events in Composition API

7aaa5c2519244ff6910d0329de4e46d0.jpeg

Emitting events allows child components to propagate events to parent components. Consider a scenario where we have a popup component and we intend to toggle its visibility from the parent component.

When a value such as showPopup is set to true, the popup should be shown, conversely, when the value is set to false, the popup should be hidden. This event-based mechanism facilitates efficient communication between components and facilitates the synchronization of their behavior.

In this case it is necessary to pass the event up to the parent component. By doing this, we can handle this event in the parent component, effectively closing the popup by changing the state showPopup to false.

This method of emitting events from child components to parent components is a valuable strategy for managing these scenarios. It allows us to handle events in a structured way, enabling seamless interaction between involved components.

define emits (DefineEmits)

In order to trigger events, we use the defineEmits macro API provided by Vue.js to declare the events to be triggered. As shown in the example below, the defineEmits macro accepts a list of events to fire. It is important to note that declarations should only be made in child components, not in parent components.

Events emitted by the statement

// emit one event "close"
const emit = defineEmits(['close'])

// emit multiple events "close" and "submit"
const emit = defineEmits(['close','submit'])

emit and listen to events

We can also pass values ​​in events. For example, when we emit certain events, we may want to pass some values. We can pass the value as the second parameter after emitting the event parameter.

In the example below, we render some items in a child component and emit an itemClicked to the parent component using its index value.

Subassembly

<script setup lang="ts">
import { ref } from 'vue';
const items = ref(['Java','Python','JavaScript','Rust','Go','C','OCalm'])
const emit = defineEmits(['itemClicked'])
function selectItem(index: number) {
  emit('itemClicked', index);
}
</script>

<template>
  <div>
    <ul>
      <li class="list" v-for="(item, index) in items" :key="index" @click="selectItem(index)">
        {
    
    { item }}
      </li>
    </ul>
  </div>
</template>

<style scoped>
ul {
  display: flex;
  padding: 0;
  list-style: none;
  column-gap: 4px;
}
.list {
  padding: 10px 18px;
  border: 1px solid darkgray; 
  margin: 4px;
  border-radius: 5px;
  cursor: pointer;
}

parent component

In the parent component, we import ChildComponent and include it in the template. We can then use the v-on directive (or @ for short) to catch custom events emitted by ChildComponent. We pass in the handleEmittedEvent method to receive the emitted value (in this case the index of the clicked item) and update the emittedValue data property in the parent component.

<template>
  <div>
  <p>Index of Clicked Item is {
    
    {emittedValue}}</p>

  <ChildComp @item-clicked="handleEmittedEvent" />
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import ChildComp from './ChildComp.vue'
const emittedValue = ref<number | null >()
function handleEmittedEvent(index: number){
    emittedValue.value = index
}
</script>

When handling custom emit events, remember to name your directives using the kebab-case naming convention. This helps maintain consistency and readability in your Vue components.

We've explored the process of emitting events in Vue.js and how to handle them in a parent component using custom directives. Emitting events in various scenarios is critical as it enhances the flexibility and efficiency of your application.

2. How to render SVG files in VueJS

fdc2941687a4d10d4e382cc73df3676d.jpeg

Scalable Vector Graphics (SVG) is based on the XML standard and is used to define images. Like other image formats, SVG can be indexed, searched, compressed, and scripted. Unlike bitmap image formats such as PNG, SVG can be rendered at any size without loss of quality.

SVGs are widely used in modern applications mainly due to their user-friendly nature and ability to maintain image quality no matter what screen size they are rendered on.

Render SVG files

In Vue.js, there are three main ways to render SVG files. One of the ways is to wrap the SVG file in a Vue.js template component, then import and use it as a component.

Another option is to use the default <img> tag to render SVG files. With this approach, you simply provide the path to the SVG file as the src attribute and the file will be displayed as an image.

SVG as template file

In this form, we can include the SVG file directly in the template tag and it will be rendered as-is. In the template below we have a carbon:at @ sign represented as an SVG image

<template>
  <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 32 32"><path fill="currentColor" d="M16 3A12.92 12.92 0 0 0 3 16v1a13 13 0 0 0 13 13h7v-2h-7A11 11 0 0 1 5 17v-1A10.94 10.94 0 0 1 16 5a10.64 10.64 0 0 1 11 11c0 3.59-1.4 5-3.66 5c-1.58 0-2.34-1.29-2.34-3v-8h-2v1.94A3.84 3.84 0 0 0 15.5 10a5.48 5.48 0 0 0-5.5 5.44v2.12A5.48 5.48 0 0 0 15.5 23a4.28 4.28 0 0 0 4-2.46A4.35 4.35 0 0 0 23.41 23c3.07 0 5.59-2 5.59-7A12.72 12.72 0 0 0 16 3Zm3 14.56a3.5 3.5 0 0 1-7 0v-2.12a3.5 3.5 0 0 1 7 0Z"></path></svg>
</template>
<script lang="ts">
export default {
  name: 'CarbonAt'
}
</script>

In Vuejs, with SVG as a file template, we can easily import and use it like any Vue component. We can also resize it by specifying width and height, just like we do with normal SVG.

<script setup>
import CarbonAt from './CarbonAt.vue';
</script>
<template>
    <CarbonAt />
</template>

SVG as image file

Another way to render SVG files is to use HTML's <img> tag to specify their location, using the src attribute. This method renders the SVG file as an image file, where the src attribute points to the location of the specific SVG file.

Since the <img> tag has the ability to render various image formats, including APNG (Animated Portable Network Graphics), AVIF (AV1 Image File Format), GIF (Graphics Interchange Format), JPEG (Joint Photographic Experts Group Image), PNG ( Portable Web Graphics), SVG (Scalable Vector Graphics) and WebP (Web Picture Format), which provide a versatile solution for integrating different types of visual content.

<template>
  <div>
    <img :src="CarbonAt" alt="image of carbon at">
  </div>
</template>

<script setup>
import CarbonAt from './CarbonAt.svg';

</script>

Use the Object tag

Another possible way to render SVG images in Vuejs is to use object tag. object is used when you want more control over how the SVG file is rendered.

<template>
  <div>
    <object :data="svgUrl" type="image/svg+xml"></object>
  </div>
</template>

<script setup>
const svgUrl = 'https://api.iconify.design/carbon:branch.svg';
</script>

Rendering SVG files into your Vue.js application can dramatically improve its performance and bring many advantages.

3. How to monitor the content changes of the file upload form

bae5ca08d88ed84a14f75576f0f77aa6.png

Sometimes, we want to observe the file input in Vue.js in order to catch the file selection change event.

We can observe the file selection change event of the file input in Vue.js by listening to the change event. To do this, we use the @change directive to write:

<template>
  <div id="app">
    <input type="file" @change="previewFiles" multiple />
  </div>
</template>
<script>
export default {
  name: "App",
  methods: {
    previewFiles(event) {
      console.log(event.target.files);
    },
  },
};
</script>

Also, we set the value of @change to the previewFiles method.

Then when we select a file using the file input, we can get the list of files for the selected file via the event.target.files property.

We can also assign a reference to the file input and use it within the method to refer to the file input.

To do this, we can write:

<template>
  <div id="app">
    <input type="file" ref="myFiles" @change="previewFiles" multiple />
  </div>
</template><script>
export default {
  name: "App",
  methods: {
    previewFiles() {
      console.log(this.$refs.myFiles.files);
    },
  },
};
</script>

We set the ref property to myFiles and then use this.$refs.myFiles.files to get the selected files.

We can observe the file selection change event of the file input in Vue.js by listening to the change event. Also, we set the value of @change to the previewFiles method.

4. How to delete an attribute from a data object?

ec58d828c90f449ebac1a755a2fe8f6b.jpeg

Sometimes, we want to remove a property from a data object using Vue.js. In this article, we'll cover how to remove properties from data objects using Vue.js.

To delete a property from a Vue.js data object, we can use the this.$delete method. For example, we can write:

<template>
  <div id="app">
    {
    
    { users }}
  </div>
</template>
<script>
export default {
  name: "App",
  data() {
    return {
      users: {
        foo: { firstName: "jane", lastName: "smith" },
        bar: { firstName: "john", lastName: "green" },
      },
    };
  },
  mounted() {
    this.$delete(this.users, "foo");
  },
};
</script>

Use the this.$delete method to delete the foo property from the this.users reactive property.

The $delete method will trigger Vue's reactivity to update the this.users object to delete the foo property.

So, from the template, we should see that users is now:

{ "bar": { "firstName": "john", "lastName": "green" } }

We can also use the Vue.delete method to do the same thing, written as:

<template>
  <div id="app">
    {
    
    { users }}
  </div>
</template>
<script>
import Vue from "vue";
export default {
  name: "App",
  data() {
    return {
      users: {
        foo: { firstName: "jane", lastName: "smith" },
        bar: { firstName: "john", lastName: "green" },
      },
    };
  },
  mounted() {
    Vue.delete(this.users, "foo");
  },
};
</script>

We just replaced this.$delete with Vue.delete .

To delete a property from a Vue.js data object, we can use the this.$delete method. We can also use the Vue.delete method to do the same thing.

5. How to gracefully handle front-end API errors?

06d59933d609ced578a724bcfb164133.jpeg

Application programming interfaces (APIs) provide a way to communicate and exchange information with different services. However, during the communication process, there are potential points of failure. For example, when querying an API for user data, the API may not find records, permissions may be limited to view certain information, or the server may fail completely. Between communication layers, some problems may arise.

In our front-end application, if we don't handle most of these edge cases and report meaningful information to the user, the user won't be able to know what went wrong, which can lead to a poor user experience.

A perfectly implemented front end has to handle all possible edge cases to provide a smooth user experience. In this article, we'll explore effective and efficient ways to handle API errors, provide meaningful feedback to users and guide them to resolve issues.

The implementation below already handles various edge cases and reports meaningful information. please look below. Our goal is to handle most edge cases and display an informative prompt on any errors.

<template>
  <h1>Get Bookmarks</h1>
  <button @click="fetchUserBookmarks">Bookmarks</button>
</template>

<script setup lang="ts">
import axios, { AxiosError } from "axios";
import { useToast } from 'vue-toastification';
const url = 'https://api.example.com';
const toast = useToast();
const fetchUserBookmarks = async () => {
  try {
    const response = await axios.get(url);
    // Handle the data as needed (e.g., update state, display bookmarks, etc.)
    const data = response.data;
    console.log(data);
  } catch (error: any) {
    handleError(error)
};
function handleError(error: unknown){
  if (error instanceof AxiosError && error.response) {
      // Check for specific status codes and show toast messages accordingly
      const statusCode = error.response.status;
      if (statusCode === 404) {
        toast.error('Not found: The requested resource was not found.');
      } else if (statusCode === 429) {
        toast.warning('Rate Limited: Too many requests, please try again later.');
      } else if (statusCode >= 500) {
        toast.error('Server Error: An internal server error occurred.');
      } else if (error.message === 'Network Error') {
        //implement retry here
        toast.error('No internet connection. Please check your network connection.');
      }
    } else if (error.request) {
      // The request was made, but no response was received
      toast.error('No response received from the server.');
    } else {
      // A different error occurred here
      toast.error('An unexpected error occurred:');
      console.log(error)
    }
  }
}
</script>

When dealing with front-end API error handling, there are some best practices to consider.

Implement catch blocks: Wrap API requests in try-catch blocks to handle exceptions and errors gracefully. This prevents the entire application from crashing due to unhandled API errors.

Parsing error responses: APIs typically return detailed error responses in JSON format. These responses are parsed to extract relevant information, such as error messages or error codes, and presented to the user in a user-friendly manner.

Use HTTP status codes: Pay attention to the HTTP status codes returned by the API. Different status codes indicate different types of errors (for example, 404 for Not Found, 500 for Server Error). Handle each status code appropriately in your front-end code.

Display user-friendly messages: Display clear and concise error messages to the user, describing what went wrong, and providing directions for resolving the problem. Avoid showing raw technical details to end users, as this can be confusing and even a security risk.

Log Errors: Log API errors on the client side to gather valuable data for debugging and troubleshooting. However, be careful not to log sensitive information in a production environment.

Retry Mechanism: Implement a retry mechanism for transient errors (such as network timeouts) so that the API has a chance to recover from temporary problems. However, avoid excessive retries to prevent overloading the API and triggering the rate limiting mechanism.

Timeout: Set a reasonable API request timeout to prevent the frontend from waiting indefinitely for a response. Consider providing a user-friendly message if a request times out.

Handle network errors: In addition to handling API-specific errors, also handle network errors such as connection failures or CORS (Cross-Origin Resource Sharing) issues. Display an appropriate message or direct the user to check their internet connection.

Provide contact information: In the case of critical bugs or issues, consider providing contact information or a support link so users can report issues or seek assistance.

Localization: If your application is internationalized, make sure that error messages are also localized to meet user needs in different regions.

Automated tests: Write automated tests to simulate API errors and ensure that error handling mechanisms work as expected.

Security Note: Be careful not to expose sensitive information in error messages, as an attacker could use this data to learn about the system's vulnerabilities.

By following these API error handling best practices, you can build a front-end application that handles errors efficiently, maintains a smooth user experience, and provides useful feedback to users when problems occur unplanned.

Finish

Due to the limited space of the article, today’s content will be shared here. At the end of the article, I would like to remind you that the creation of articles is not easy. If you like my sharing, please don’t forget to like and forward it, so that more people in need See. At the same time, if you want to gain more knowledge of front-end technology, welcome to follow me, your support will be the biggest motivation for me to share. I will continue to output more content, so stay tuned.

Guess you like

Origin blog.csdn.net/Ed7zgeE9X/article/details/132572464