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 process of Defining an Element Based on Two Attributes in C#?

Is it feasible to specify a web page element based on two attributes? For example, I can locate the element by its innertext Element imagePage = ActiveBrowser.Find.ByContent(pageNumbers[p],FindContentType.InnerText); Alternatively, I can identify an ele ...

Loop through the elements of one array using the indexes from a second array

Hey there! I need help with the following code snippet: let names = ["josh", "tony", "daniel"]; let arrayplaces = ["30", "60", "90"]; names.forEach((elem, indexed) => { const num2 = arrayp ...

Verifying a user's name when navigating a route

Hey everyone, I've been working on this project for the past 3 hours and could really use some help. I created an express webapp with an admin page. The register and login functionalities are all set up using passport. I have a function to check if th ...

The JavaScript filter function will only return arrays that have matching IDs

How can I filter out book data based on the author's id? I have a list of books with various author ids, and I want to only return the books that match a specific author id. However, my current filtering method doesn't seem to work correctly as i ...

Controller encounters a error when requiring a module

Struggling to set up Stripe for my app, I've encountered some issues with the module implementation. Typically, I would require a module at the top of the file to use it. However, in the paymentCtrl file, when I do this, it doesn't work and I rec ...

Vue i18n locale update does not always immediately reflect in all components

Currently, I am developing a web application utilizing the **Vue framework**, and for internationalization purposes, I am implementing vueI18n. However, I have encountered a problem where changing the language locale does not immediately reflect in all com ...

JavaScript takes the spotlight before CSS

Currently experiencing this issue in Chrome, although Firefox seems to be working fine so far. Here is a greatly simplified version of the problem: HTML: <div class="thumbnail"> <a href='#' id="clickMe">Click me!</a> </d ...

What is the reason behind localStorage.getItem consistently returning a string value?

Something strange is happening. In the lib.dom.d.ts file, the type for localstorage.getItem shows as 'string | null', but in my app it always returns a string. Why is this discrepancy occurring? ...

Unraveling JSON data retrieved from a MySQL query

After successfully encoding a MySQL result from PHP into JSON, I am now faced with the task of decoding it using JavaScript. Let's assume that my string returned is: [{"0":"x","1":"z"},{"0":"xs","1":"zz"}] I would appreciate some guidance on how to ...

Adjust the color of TextareaAutosize component using mui in React

Just starting out with React and getting acquainted with mui components. Experimenting with setting the color of a TextareaAutosize mui component using this code: import * as React from 'react'; import TextareaAutosize from '@mui/material/T ...

The error message that keeps popping up is saying that it cannot access the property "username" as it is undefined

signup.js const SignupForm = () => { const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const handleSignup = () => { fetch("/signup", { method: "post", header ...

Issues with the functionality of the Handlebars template are causing it to

Currently experimenting with Handlebars templates within my express/node.js application. I have created a template and corresponding .js files, but unfortunately, they are not functioning as expected. While the page correctly displays the unordered list&ap ...

Choose the item to automatically reposition itself below once it has been opened

issue : The current behavior is that when the "other" option is selected, the input field appears. However, if I click on the select again, it covers up the input field. desired outcome : Ideally, I want the input field to show up when the "other" option ...

Unable to locate the AngularJS controller after attempting to paste the code

Currently enrolled in the AngularJS Mastery Course on Udemy, I encountered an odd issue that has left me scratching my head. The code provided seems to function flawlessly for most users, except for a select few. index.html <html lang="en" ng-app=&apo ...

Troubleshooting JavaScript Integration in PHP Scripts

I'm currently working on creating an advertisement switcher that can display different ads based on whether the user is on mobile or desktop. I've tried inserting PHP includes directly into the code, and while it works fine, I'm struggling t ...

Problem with Vue Router in Laravel subroute leading to incorrect component discovery

While I had a similar setup working smoothly on another Laravel/Vue project with the main route /, I encountered an issue when grouping the Vue instance under an admin subroute. All paths entered after "admin" would redirect to a PageNotFound component tha ...

Tips for retaining the scroll position of a particular page after a postback

I am working on a grid to display data row by row. Each row is displayed using a user control. When I scroll to the bottom of the page and click on a row, it redirects me to a view page for that specific row. However, when I click on the back link, I would ...

What is the best way to link assets within an Angular custom element (Web Components)?

After successfully creating a web component and referencing an image from my asset folder, everything was running smoothly on my local environment. However, when I published my custom element to Firebase hosting, I encountered some issues. When trying to ...

Determining the dimensions of a div with a scrollbar using Jquery

Is there a way to get the width and height of a div with scroll that includes both visible and hidden content using JQuery? If anyone has a solution for getting these values, please share. <div id="area" class="divLeftCem area"> <div id="pan ...

How can I choose records from collection 'x' in mongodb?

I need to fetch all fields from my database using an API call Here is my code: exports.objfields = async (req, res, next) => { try { var db = mongo.connection; var objeto = req.headers.objeto; const result = db.db.collection(objeto).find( ...