Can custom directives in Vue be used to define data variables?

I am using two components: SceneList and SceneCard. In the SceneList component, I am randomly setting the background color of each SceneCard and trying to pass the color code to the SceneCard component. However, I am encountering an error message: "Error in directive rainbow bind hook: 'TypeError: Cannot set property 'bgcolor' of undefined'". Can anyone suggest a proper way to set data in custom directives?

Below is my code:

SceneList:

<template>
  <div id="scene-list">
    <scene-card
      class="scene-card-comp"
      v-for="scene in scenes"
      :key="scene.id"
      :bgcolor="bgcolor"
      v-rainbow>

    </scene-card>
  </div>
</template>

<script>
import SceneCard from './SceneCard.vue';
export default {
  props: ['scenes'],

  components: {
    SceneCard
  },

  data() {
    return {
      bgcolor: null
    };
  },

  directives: {
    rainbow: {
      bind(el) {
        const bgColor = `#${Math.random().toString().slice(2, 8)}`;
        el.style.backgroundColor = bgColor;
        this.bgcolor = bgColor;
        el.style.opacity = '0.5';
      }
    }
  }
};
</script>

<style lang="less">
...
</style>

SceneCard:

<template>
  <div id="scene-card" @click="changeBGColor">

  </div>
</template>

<script>
export default {
  props: ['bgcolor'],

  data() {
    return {

    };
  },

  methods: {
    changeBGColor() {
      console.log('bgcolor change ', this.bgcolor);
    }
  },
};
</script>

Answer №1

If you want to customize your component, remember to use el instead of this as it directly refers to the component itself.

el represents both the HTML DOM and the component as mentioned in the documentation (https://v2.vuejs.org/v2/guide/custom-directive.html)

    rainbow: {
        bind(el, /* binding, vnode */) {
            const bgColor =`#${Math.random().toString().slice(2, 8)}`;
            el.style.backgroundColor = bgColor;
            el.bgcolor = bgColor;
            el.style.opacity = '0.5';
           }
        }

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

Create bubble diagrams to display detailed information within a line graph using Chart.js

After creating a line chart with chartJS, I am looking to enhance it by adding bubbles to indicate specific data points such as the mode, red, and amber levels. While I have successfully drawn the lines on the chart, I am unsure of how to incorporate these ...

Troubleshooting a Multi-dimensional Array Reference Issue

Currently, I am working with an Array and need to modify the last item by pushing it back. Below is a simplified version of the code: var array = [ [ [0,1,2], [3,4,5] ] ]; //other stuff... var add = array[0].slice(); //creat ...

Cannot choose an option using JQuery Select2

Encountering an issue with Select2. The functionality seems to be working fine, except for the inability to select any option. Utilizing select2 version 3.5.3 along with KnockoutJS, CoffeeScript, and JQuery. Here is my select2 code: generateSelect3 =-> ...

Ways to manage an excessive number of asynchronous calls?

As a newcomer to Node, I've learned that writing synchronous functions can negatively impact the event loop by causing it to lock up. It's generally better to write everything asynchronously. However, there are cases where using async for everyt ...

What is the best way to establish a default rejected promise behavior for all of my Express middleware functions?

Using promises within express middleware and wanting to switch to async/await methods. app.get('/data1',async function(req,res) { data = await getData1(); // Error occurs here res.send(data) }) app.get('/data2',async function(r ...

What could be causing a React component to render two times in a row?

While analyzing the render function of a component, I have noticed that it is executed twice at times, if not most of the time. Could this be due to the first render occurring before the component receives any props, with the second render happening once ...

How to accentuate search results using Angular filters and conceal non-matching text?

Recently, I came across an interesting example of using Angular filter to highlight search results. It works well in highlighting the word 'suit', but I noticed that all non-matching text remains visible. If you'd like to see the example I ...

Managing two simultaneous web service calls in Angular 2

Dealing with two parallel web service calls can be tricky. Sometimes the first call goes through first, and other times it's the second one. The problem arises when the function in my second service requires data from the first service call. I attemp ...

Ways to verify if a chosen dynamic form input satisfies specific requirements

I just started learning Angular and I'm struggling with the nested JSON logic. I am aiming to create a dynamic form and found inspiration from this helpful tutorial. My goal is to implement conditional fields that only display when a specific option ...

What is the process for loading Syntax Highlighter on pages with pre tags?

As a Blogger, I often find myself in need of demonstrating codes on my blog. To achieve this, I have been using a Syntax Highlighter developed by Alex Gorbatchev. However, a recurring issue I face is that the files load on every single page of my blog, cau ...

Utilizing Async/Await in conjunction with Vuex dispatch functionality

I'm currently working on creating a loader for specific components within my application. Here is the code snippet for one of my components: mounted() { this.loading = true; this.getProduct(); }, meth ...

Having trouble with the menu toggle button on Bootstrap 4?

When using Bootstrap 4, the breadcrumb button may not function properly when the header becomes responsive. I have ensured that Bootstrap 4 CSS and JS are included in the project. Please assist me in resolving this issue. Code: .navbar { height:100 ...

Tips for sending arguments to translations

I am currently implementing vuejs 3 using TS. I have set up my translation files in TypeScript as shown below: index.ts: export default { 'example': 'example', } To use the translations, I simply do: {{ $t('example') }} N ...

Is it necessary to configure Webpack or use a plugin to remove console.log() statements by default in an Angular Application, or does it do so automatically?

Welcome to my first post! I hope I can effectively communicate the question and the background that led me to ask it. I am relatively new to web programming, with about 1 and a half years of experience working with Java, JavaScript, and TypeScript using An ...

Looking to show a div upon clicking a link with the use of Javascript

Looking for a workaround due to restrictions on using alert or any Js dialog box, I need to create some sort of magic trick: 1. Create a div with a link named "info". 2. Develop an invisible div that will serve as my "PopUp" containing random information. ...

Determine whether the elements in the master array match the elements in the child array

Checking for data presence in arrays: [ { "productDisplay": "ZXP 105", "productNumber": "WZDR 112" }, { "productDisplay": "ZXP 106", "productNumber": "WZDR 113" } ] ChildArray [{productDisplay:"ZXP 105", ...

Blur images on parent div when hovering using javascript

After some extensive searching, I came across a few helpful explanations on how to achieve my desired outcome. By combining them, I was able to get everything working smoothly with the hover effect over the image itself. However, when I attempted to trigge ...

Enable CORS for AJAX requests with RESTful web services in Google Chrome

My web-based project is fully written in jQuery and JavaScript. On the client side, I am calling RESTful webservices via AJAX like this: $.ajax({ type: 'GET', timeout: 1000000000, headers: { 'Access-Control-Allow-Origin': ...

The Javascript Switch statement is experiencing some functional issues

I am facing an issue where I need to handle different scenarios based on a decimal value, and I thought of using a Switch/case statement for this purpose. However, the code is not working as expected. Below is the snippet of code in question: var spread ...

Send the input's value to v-model

Is there a way to automatically pass the value of the input into the v-model? Thank you :) Here is the code snippet: <input value="{{$in->id}}" v-model="upload.id"> I attempted the following in my script: upload: { bank:'', ...