What is the best way to insert CSS code into a custom Vue directive file?

I need a solution that applies a gradient background to the parent div in case an image fails to load. I've attempted to create a directive for this purpose:

export default {
    bind(el: any, binding: any) {
        try {
            .....
            img.onerror = () => {
                el.parentNode.classList.add("fallback");
            };
        } catch (e) {

        }
    },
};

The directive works with the following template:

<div><img v-image-fallback :src="xxx" /></div>

And it also includes these styles:

.fallback {
    width: 600px;
    height: 400px;
    margin: auto;
    background: radial-gradient(...);
}

Is there a way to effectively combine the directive and CSS components together? Can the two work seamlessly?

Answer №1

The existence of the parent node cannot be guaranteed until the inserted hook in Vue 2 or the mounted hook in Vue 3 is reached.

To ensure access to the parent node, switch from using the bind hook to either of the following:

// MyDirective.js
export default {
  // BEFORE:
  bind(el) {
    console.log(el.parentNode) // => null ❌ 
  }

  // AFTER (Vue 2):
  inserted(el) {
    console.log(el.parentNode) // => <div> ✅
  }

  // AFTER (Vue 3):
  mounted(el) {
    console.log(el.parentNode) // => <div> ✅
  }
}

See live demo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Making changes to an input field can impact other elements when using the v-model directive

I am facing an issue with a cart setup where the quantity of all products are being updated when I increase the quantity of one product. How can I prevent this and only update the quantity of the selected product? <div v-for="(product, index) in cartPr ...

When first accessing the page, the map may not load properly. However, a simple refresh of the page in VueJS should resolve this issue and allow the

After initially loading the page, the map may not work properly in Vue.js. However, refreshing the page fixes this issue. Can anyone provide assistance with this problem? Here is the relevant code: mounted() { this.geolocate(); }, methods: { ...

Converting Typescript library into a standalone global JavaScript file

Currently working on developing a Typescript library that follows this structure: https://i.stack.imgur.com/YyCHk.jpg This includes the following files: restApi.class.ts import { restApiOptions } from '../models/rest.options.model'; import { ...

Endpoint path for reverse matching in Mongodb API

I am currently in the process of setting up a webhook system that allows users to connect to any method on my express server by specifying a method and an endpoint to listen to (for example PUT /movies/*). This setup will then send the updated movie to the ...

The background image on Nuxt.js is not adapting to different screen sizes

My journey with developing a Nuxt app hit a snag in the CSS department early on. The issue plaguing me, as is often the case, is responsive background images. Everything looked great during testing on desktop browsers, but when I opened it up on my mobile ...

Error in Module Building: The path argument must be a string type. A different type was received, which caused the build to fail

I recently updated my Vuetify version from 1.5 to the latest 2.3.10. However, when trying to run the webpack server, I encountered this error message. Even after adding yarn add sass -D, the issue persists. Can someone please assist me in resolving this pr ...

Should front-end and back-end share Typescript data modeling through classes or interfaces?

I'm currently exploring the best approach to share the same data types between the client (React) and the server (Express + Socket.IO). Within my game, there are various rooms each storing the current status, such as: class GameRoom { players: P ...

Which is the better choice for simply invoking a service method - subscribe or toPromise?

When implementing the search method below, I simply assign the value of BehaviourSubject in the service. However, I am unsure whether it is possible to execute this operation without using either subscribe() or toPromise() after the .pipe() block in the ...

The tsconfig.json file is located separate from the project directory

Working on my project called "portal" has been quite an interesting journey. As I delved deeper into development, I realized the need for multiple projects within the repository. This led me to restructure my project setup like this: A question popped up ...

Utilizing import for Ionic3 to export const with logic

While developing an app using ionic3, I encountered an issue with setting up a proxy. When running in a browser, Ionic was able to recognize the path of my proxyUrl as shown below. ionic.config.json { "name": "myApp", "app_id": "", "v2": true, "t ...

Can Typescript restrict a value to only exist within a specified set of key names within the same object?

I am completely new to Typescript and I am fascinated by the way it can check types. One thing I would like to know is if Typescript can be used to verify at compile time whether a value's domain falls within a predefined set of key names that are de ...

Finding the specific type within a union based on its field type

I am trying to implement a function sendCommand that returns a value of type specified by the union InputActions, selected based on the action_id type. Below is my code snippet: interface OutputAction1 { command: 'start', params: string; } i ...

Twilio SMS Notification: The Class extension value provided is not a valid constructor or null

When attempting to utilize Twilio for sending SMS messages in a Vue.js project, I encountered an error while accessing Tools -> Developer Tools. <template> <div> <input type="text" v-model="to" placeholder="Phone ...

Utilize vue-resource for updating information in the database

Within my Vue component, I have the following data setup: data() { return { revenueChart: '', limit: 12, labels: '', datasets: '' } }, In addition, there is a method that utilizes vue- ...

The process of subscribing to a service in Angular

I currently have 3 objects: - The initial component - A connection service - The secondary component When the initial component is folded/expanded, it should trigger the expansion/folding of the secondary component through the service. Within the service ...

Encountering a TypeError stating that the "option is undefined" error has occurred

Unexpectedly, my dropdown menu that was functioning perfectly fine is now throwing an error. I've made several changes and none of them seem to resolve the issue. Could it be a data type mismatch or am I missing something crucial here? Your insights ...

The Vue CLI is failing to pick up SocketIO events

Working on a Chat Application using VueCLI and Nodejs, I have set up proxy connections and everything seems to be functioning well. However, my VueCLI component is not listening to emit events from the server. The "sockets" object in the vue component is ...

Issues in the d3.js chart

I'm facing an issue with some incorrect lines appearing in my d3.js chart. Strangely, the problem seems to disappear when I switch tabs on Chrome and return to the chart's tab. It's puzzling to figure out the root cause of this issue, so I ...

Separate the generic function interface into its own type/interface variable

Below is an example of TypeScript generics that I found on typescriptlang. function getProperty<Type, Key extends keyof Type>(obj: Type, key: Key) { return obj[key]; } let x = { a: 1, b: 2, c: 3, d: 4 }; getProperty(x, "a"); getProperty ...

What is the best way to trigger an API call every 10 seconds in Angular 11 based on the status response?

I am in need of a solution to continuously call the API every 10 seconds until a success status is achieved. Once the success status is reached, the API calls should pause for 10 seconds before resuming. Below is the code I am currently using to make the A ...