Guide to using a Selector in a mixin in VUE

I'm attempting to create a Mixin that will help me calculate the offsetWidth of an element.

Here is my Mixin:

export const boxWidth = (selector) => ({
  mounted() {
    selector.addEventListener(
      'resize',
    this.setBoxWidth
  );
},
methods: {
  setBoxWidth(e) {
   let box = e.target;
   this.myBoxWidth =  box.offsetWidth;
   console.log(this.myBoxWidth);
  }
}
})

I am trying to use this Mixin in a component:

<template>
  <div
    ref="visuraBox"
    class="container"
  >
    <div class="field">
      <label class="label">Name</label>
      <div class="control">
        <input
          class="input"
          type="text"
          placeholder="e.g Alex Smith"
        >
      </div>
    </div>
    <div class="field ">
      <label class="label">Name</label>
      <div class="control">
        <input
          class="input"
          type="text"
          placeholder="e.g Alex Smith"
        >
      </div>
    </div>
  </div>
</template>

<script>
import { boxWidth } from '../mixins/boxWidth'

export default {
  name: 'VisuraCatForm',
  mixins: [boxWidth(this.$refs.visuraBox)],
  data() {
    return {
      myBoxWidth: 0
    }
  },
  created() {
    const myBox = this.$refs.visuraBox
    this.myBoxWidth = myBox.offsetWidth;
  }
}
</script>

<style lang='scss' scoped>
@import '@/assets/design/components/_form.scss';
</style> 

However, since the ref doesn't exist yet, I'm left wondering: How can I pass a selector inside a mixin? (P.S. I'd rather not declare the mixin globally)

Answer №1

Just a little further to go...

My advice would be to incorporate a function into your mixin that manages the existing functionality currently found in the mounted hook of the mixin:

handleResizeEvent(selector) {
    selector.addEventListener('resize', this.adjustBoxWidth);
}

Subsequently, you can invoke this fresh method from the mounted hook of your initial component.

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

What is the best way to conceal selected options in a MUI multiselect in the select field?

I'm currently working with a MUI multiselect feature to allow for the selection of multiple options from a dropdown menu. However, I am facing an issue where I do not want the selected options to be visible within the dropdown field. Is there a way to ...

Pass the returned variable value from a request.get call to another function in NodeJS Express

I have a situation where I am calling a function that makes a request to get some JSON data and then fills in the variables from my router.get method. The issue I am facing is that the variables are getting their value inside the callFunc function, but wh ...

Receive JSON data with camel-case in a Web API 2.0 using a model in pascal-case style

My attempt to execute a PUT call on my Web API involves configuring the WebApiConfig.cs file to send data back to my Web project in camel case format. config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesCont ...

Implementing AngularJS to display different divs according to the selected value

I am attempting to utilize the value of an HTML select element to toggle the visibility of specific div tags using AngularJS. Below is the code snippet I have been working with: <body ng-app="kiosk" id="ng-app" > <div class="page" ng-controll ...

Modify CSS using Javascript by targeting the class of ".modalDialog > div {}"

I am currently working on a project that involves creating a Modal Layer using CSS. I have successfully implemented the modal layer, but now I need to figure out how to change the width from the default 400px to something else when I open it with Javascrip ...

Steps for adding a favicon to Content-Type: application/json

In my implementation using node.js, I have an API that returns a response with Content-Type: application/json. Here is an example: module.exports={ api: (req, res) => { let data = {"data": [1, 2, 3]}; res.status(200).json(d ...

Tips for organizing JSON object data and displaying it appropriately on an HTML page

This code utilizes ajax: $("form").on("submit", function () { var data = { "action": "test" }; data = $(this).serialize() + "&" + $.param(data); $.ajax({ type: "POST", dataType: "json", url: "ajax2.php" ...

Using Array.push to add an object retrieved from a Redis cache in a Node.js application is causing issues and is not functioning as expected

I've encountered a problem with retrieving all keys from my Redis cache, storing them in an array, and sending that array to the user using Express. The issue arises when I receive an empty array as the response with no objects in it. I attempted to u ...

What is the best way to remove the excess numbers from the return date provided by the react-date-picker?

I need help displaying only the Month and Day with the format "Tue Oct 22 2019". Currently, I am getting "Tue Oct 22 2019 00:00:00 GMT-0700 (Mountain Standard Time)" when using "react-date-picker". How can I achieve this without having to truncate the te ...

What is the best way to pass the value from one textfield to another using material UI in a react application?

I'm looking to transfer the content from a text field in a dialog window to another text field that is not embedded. However, instead of transferring the actual text field value, I'm getting an output of "object Object". Can you help me figure ou ...

Binding Events to Elements within an AngularJS-powered User Interface using a LoopIterator

I am working with an Array of Objects in AngularJS that includes: EmployeeComments ManagerComments ParticipantsComments. [{ "id": "1", "title": "Question1", "ManagerComment": "This was a Job Wel Done", "EmployeeComment": "Wow I am Surprised", ...

Utilizing JSON and CodeIgniter within HTML elements

I am interested in creating a private chatroom using CodeIgniter and JSON format. I want the JSON data retrieved to be displayed in a list structure like <ul><li>messageinJSON</li></ul>. This formatting will allow me to customize th ...

Revise a catalog when an object initiates its own removal

When rendering a card in a parent component for each user post, all data is passed down through props. Although the delete axios call works fine, I find myself having to manually refresh the page for updates to be displayed. Is there a way to have the UI ...

Setting the font size for the entire body of a webpage globally is ineffective

Technology Stack: Nuxt.js + Vuetify.js Problem: Unable to set global body font size Solution Attempt: I tried to adjust the body font size to 40px in ~/assets/style/app.styl: // Import Vuetify styling ...

Puzzling array challenge. Lack of clarity in explanation

I am currently working on a series of JavaScript tests available at js-assessment One of the tasks states: it("you should be able to find all occurrences of an item in an array", function() { var result = answers.findAllOccurrences('abcdefab ...

Assign the value/text of a div element by using JavaScript/jQuery within a PHP loop

I'm struggling to figure out how to set the value/text of a div using javascript/jquery inside a loop. Can anyone offer some guidance on this issue? Goals: Extract data from a database. Use javascript/jquery to assign the extracted data to an eleme ...

Swap out the string variable when it is modified

To generate a string inside the "code" variable that combines the selected image values, the final code should appear similar to: "test1/A=1a/B=1b" or "test2/A=1b/B=1a", etc. If the user modifies icon "A," it should replace the value in the code instead of ...

What is the best way to implement a switch case with multiple payload types as parameters?

I am faced with the following scenario: public async handle( handler: WorkflowHandlerOption, payload: <how_to_type_it?>, ): Promise<StepResponseInterface> { switch (handler) { case WorkflowHandlerOption.JOB_APPLICATION_ACT ...

I am having trouble getting the filter functionality to work in my specific situation with AngularJS

I inserted this code snippet within my <li> tag (line 5) but it displayed as blank. | filter: {tabs.tabId: currentTab} To view a demo of my app, visit http://jsfiddle.net/8Ub6n/8/ This is the HTML code: <ul ng-repeat="friend in user"> ...

What is the best way to arrange the keys within a nested object in JavaScript?

Question: { "foo": "bar", "bar": "baz", "baz" : { "nestedKey": "foo" } } In order to sign this request using the Hmac512 algorithm, I must first stringify the object. I am concerned that if the key order is not preserved, the generated signature on the ...