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

An error occurs when attempting to access a property that does not exist on type 'never'. Why is this considered an error rather than a warning?

I am experiencing an issue with the following code snippet: let count: number | undefined | null = 10; count = null; let result: string | undefined | null = count?.toFixed(2); console.log(`Result: ${result}`); The error message I received is as follows: ...

Leveraging the power of Framer Motion in combination with Typescript

While utilizing Framer Motion with TypeScript, I found myself pondering if there is a method to ensure that variants are typesafe for improved autocomplete and reduced mistakes. Additionally, I was exploring the custom prop for handling custom data and des ...

Angular-Slickgrid: Some filters may not display on the header row

After thorough investigation and experimentation, I was able to identify both the issue and a suitable solution: The problem stemmed from our dataset's usage of numeric IDs (e.g. 1,2,3,...). Within the code, there was an error where the grid misinter ...

Setting the content-type for static assets in NuxtJS

I'm trying to use the Nuxt built-in server to serve the static file /.well-known/apple-app-site-association with a content-type of application/json. Unfortunately, because the file does not have a .json extension, it is returning as application/octet- ...

What could be causing the issue with the navigation circles on my carousel not updating when clicked?

I created my own carousel from scratch and it's working perfectly fine except for one issue - clicking on the navigation circles. When using the interval/infinite loop prop, the circles update to the correct active slide as expected. The same goes fo ...

Handle and manage errors within the controller in Express.js to prevent the further execution of asynchronous functions

Consider a scenario where there is an API endpoint /register, designed to register new users in an application. The function utilized is asynchronous, as an attempt is made to incorporate an asynchronous process within an AuthController when performing pas ...

Requirements for Method Decorators - The complete path of the class module using the decorator must be provided

Upon running the decorator (method decorators) function, we are provided with access to target, methodName, and descriptor. I am seeking the module path for target in this specific scenario. Essentially, I want the file path that points to the module that ...

Challenges with managing VueJS methods and understanding the component lifecycle

I'm facing an issue with my code. The function retrieveTutorials() is not transferring the information to baseDeDatosVias as expected. I've attempted to change the function to a different lifecycle, but it hasn't resolved the problem. The so ...

Toggle the visibility of table row dynamically with the help of bootstrap-vue

Is there a method to dynamically toggle the visibility of a table row in a dynamic bootstrap-vue table? Currently, I am utilizing the _rowVariant prop to generate a class on the row, which functions correctly. However, I am facing challenges in connecting ...

Combining files/namespaces/modules in Typescript: How to do it?

Even though I believe the solution may be simple, understanding how to merge enums across multiple files is eluding me when reading through the documentation. // a.ts enum Color{ RED, BLUE } // b.ts enum Day{ MONDAY, TUESDAY } // c ...

AXIOS does not support PUT requests, unlike POSTMAN which handles them flawlessly

Currently, I am facing an issue in updating a record within the database using C# ASP.NET as the backend and Vue.js as the frontend. While the GET and POST methods are functioning properly with both POSTMAN and AXIOS, the PUT method works only with POSTMAN ...

Setting up environment variables using Azure variables in a Vue project

I am currently working on a Vue project deployed on the Azure DevOps platform. I have set up some variables in the release process and now I want to utilize them within my project. In my company, there is an Angular project that uses env.js with the follo ...

Ways to merge two arrays into one in React JS

Here are two arrays presented below: const arrayA = { 0: { id: XXXXXXX, name: "test" }, 1: { id: YYYYYYY, name: "example" } } const arrayB = { 0: { id: XXXXXXX, category: "sea", } 1: { id: YYYYY ...

What is preventing type guarding in this particular instance for TypeScript?

Here is an example of some code I'm working on: type DataType = { name: string, age: number, } | { xy: [number, number] } function processInput(input: DataType) { if (input.name && input.age) { // Do something } e ...

Absolute imports in create-react-app do not function properly when using yarn v2 workspaces alongside typescript

I am currently utilizing yarn v2 workspaces, and within my workspaces, I have a frontend project built using create-react-app / react-scripts. My goal is to enable absolute imports in the frontend application so that I can simply do things like import Butt ...

The declaration file for the 'react' module could not be located

I was exploring Microsoft's guide on TypeScript combined with React and Redux. After executing the command: npm install -S redux react-redux @types/react-redux I encountered an error when running npm run start: Type error: Could not find a decla ...

Object with Array of Unique Values in Vue.js

Need assistance with pushing a unique Array into an Object using the key Name I attempted the following code but it seems to not be functioning correctly. Any guidance on this issue? Thank you! addArray(){ if (!this.sessions.hasOwnProperty(name)) { ...

What is the best way to retrieve the updated value following a mutation in Vuex?

In my Vuex module, I have a simple setup for managing a global date object: import moment from 'moment'; const state = { date: moment() } // getters const getters = { date: state => state.date, daysInMonth: state => state.dat ...

When using ngx-slider in Angular, it unexpectedly fires off when scrolling on mobile devices

I am currently developing a survey application that utilizes ngx-sliders. However, I have encountered an issue on mobile devices where users unintentionally trigger the slider while scrolling through rows of slider questions, resulting in unintended change ...

Avoiding the use of numbers in v-if in Vue.js

My website features a left menu that displays different content based on the selected menu's ID. However, I currently have === 0 and === 1 in the v-if statement, and I'm looking for a way to avoid manually inputting these numbers. <template& ...