Trigger Vue to pass a reference of a different element when clicked

Hello, I'm looking to retrieve an element by its class name or some other method. Specifically, I want to target an element with the class name "nav" when a menu item is clicked within my code. I've tried using refs but can't seem to get it working in this scenario.

For reference, here is the fiddle showcasing my issue: https://jsfiddle.net/cihanzengin/aq9Laaew/294154/

Below is the code snippet:

<div id="app">
        <some-component  @get-element="getElement"></some-component>
    </div>

    <script>
        var someComponent = Vue.component("some-component", {
        template: `
            <div class="columns mobile-navigation">
            <div class="column drawer">
                <a class="is" @click="$emit('get-element')">MENU</a>
            </div>
            <div ref="nav" class="column mobile-nav-wrapper">
                <p> Some Text </p>
            </div>
            </div>
        `
        });

        var app = new Vue({
        el: '#app',
        data: {

        },
        components: {
            "mobile-nav": mobileNav
        },
        methods: {
            getElement() {
            console.log(this.$refs.nav);
            }
        }
        });
    </script>

Answer №1

Here is a suggestion you can try out:

var classToCheck = 'myclass';

if( this.$refs.nav.classList.includes(classToCheck) ){
 // Code for when the above class is included
}

Alternatively, you can use the following method:

myclickevent(event){

    event.target.classList // This will give you the classList of the clicked element for comparison

}

This code snippet retrieves all the classes assigned to your element:

this.$refs.nav.classList

Answer №2

After much searching, I finally discovered the solution:

To access the ref inside JSX, you need to include **<some-component>** in the ref attribute.

Once this is done, you can access the nav ref with: this.$refs.someRef.$refs.nav

<div id="app">
        <some-component  @get-element="getElement" ref="someRef"></some-component>
    </div>

    <script>
        var someComponent = Vue.component("some-component", {
        template: `
            <div class="columns mobile-navigation">
            <div class="column drawer">
                <a class="is" @click="$emit('get-element')">MENU</a>
            </div>
            <div ref="nav" class="column mobile-nav-wrapper">
                <p> Some Text </p>
            </div>
            </div>
        `
        });

        var app = new Vue({
        el: '#app',
        data: {

        },
        components: {
            "mobile-nav": mobileNav
        },
        methods: {
            getElement() {
            console.log(this.$refs.someRef.$refs.nav);
            }
        }
        });
    </script>

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

Ways to mimic an Angular directive with a required field

Recently, I encountered a challenge that involves two directives: directive-a, directive-b. The issue arises because directive-b has a `require: '^directive-a' field, which complicates unit testing. In my unit tests, I used to compile the direc ...

Testing the functionality of an Express.js application through unit testing

I'm currently working on adding unit tests for a module where I need to ensure that app.use is called with / and the appropriate handler this.express.static('www/html'), as well as verifying that app.listen is being called with the correct p ...

Using a Dynamic Function to Replace the jQuery Global Object Variable

In a global object, there are settings that need to be updated based on user input. For instance, if "no" is selected for div 1, not only will div-one be hidden, but the variable's value will also change to 0. The problem lies in the dynamic function ...

Vue router beforeRouteEnter - when the page is refreshed, the button label vanishes

<script> export default { name: 'TEST', data() { return { prevRoute: '' } }, methods: { goBack() { return this.$router.go(-1); }, }, beforeRouteEnter(to, from, next) { next(vm => { ...

Tips for consolidating outputs from three different APIs using JavaScript and AJAX? [Pseudo code example]

For my school project, I am working on an e-commerce aggregator site where I need to combine product data from 3 different APIs (like Aliexpress and Amazon) into one homepage. Although I can retrieve results from each API individually, I'm facing chal ...

I am looking to retrieve a specific input value from a JSON array using JavaScript

I have created an array called 'PROPERTIES' which accepts values like username, password, sid, etc. I am looking to retrieve these entered values using JavaScript. 'PROPERTIES': {'gatewayurl': {'Name': ...

Unable to access $_POST parameters in PHP when making an Ajax request

My HTML file is shown below: <script> var xml = new XMLHttpRequest(); xml.onreadystatechange = function(){ if (xml.readyState === 4 && xml.status === 200) { console.log(xml.responseText); } } xml ...

Utilizing vuex for Apollo pagination

Trying to incorporate vuetify's pagination component with the nuxtjs@apollo module has been quite a challenge for me. I'm facing difficulties making it work seamlessly with my vuex store. To avoid overwhelming you, I'll skim through most o ...

The component name "pages/product/_slug.vue" is invalid as it does not adhere to the valid custom element name specified in HTML5

Currently, I am working with Nuxt.js and dealing with some dynamic routes. The folder structure I have set up looks like this: - pages - product - _slug.vue For linking to the route, I am using the following code: <nuxt-link :to="{ name: 'pro ...

Strange behavior observed when transclusion is used without cloning

During my experimentation with transclusion, I wanted to test whether the transcluded directive could successfully locate its required parent directive controller after being transcluded under it. The directives used in this experiment are as follows: - Th ...

Is it necessary to test the main.js file in Vue.js project?

While performing unit tests on components is acceptable, after running coverage analysis I have noticed that certain lines of code in the main.js file remain uncovered. This raises the question: should the main.js file also be included in testing? Specifi ...

Submit multiple forms using dojo's xhrGET method

I am searching for a solution on how to use ajax to submit multiple forms in one xhr.post call using dojo. The documentation mentioned below at the end of this page states: Actually, the attribute "form:" can be set on any node, not just form nodes. I ...

AngularJS confirmation directive for deleting items

I am currently utilizing this directive for a confirmation prompt when deleting an app. However, regardless of whether I click cancel or yes, the app still gets deleted. <small class="btn" ng-click="delete_app(app.app_id)" ng-show="app.app_id" ng-con ...

Whenever I click on <a href="whatever.aspx"></a>, I would like the page to be displayed within the current page

This is the code I am working with: <asp:DataList ID="dlGallery" runat="server" RepeatLayout="Flow" Width="100%" CellPadding="4" ForeColor="#333333"> <AlternatingItemStyle BackColor="White" ForeColor="#284775" /> <FooterStyle BackColor ...

Exploring the Challenges of Dynamic Routing in ReactJS

I have a set of components that I need to convert into dynamic URLs. When accessing the browser, for example, http://localhost:3000/houses/1, I want it to display House 1. Everything else in the application is functioning correctly. I just need to resolve ...

Can the useEffect hook prevent the page from rendering?

Is there a way to have a slight delay every time the user visits or reloads the page in order to allow for content loading? Currently, I am using a useEffect() with a setTimeout() function that sets the variable isLoading to false after 1 second. However, ...

How can one access a specific element by its id that is located within an ng-template in Angular 6?

I have a question regarding accessing a button element inside an ng-template tag using its id in the TypeScript file. How can I accomplish that without encountering undefined errors? This is what I have tried so far: HTML <ng-template #popup > ...

Is there a way to identify which specific item in a watched array has been altered in VueJS?

Imagine having an array declared in the data section like this: data() { return { myData : [{foo:2, bar:3},{foo:4,bar:5}] } } If you want to identify when the bar property of the second element changes, what should your watch function look li ...

The data in the partial view is not being properly shown by using ng-repeat

Welcome to my code snippets! var app = angular.module("AppModule", ["ngRoute"]); app.factory("DataSharing", function () { return { value: 0 } }); // Setting up Routing app.conf ...

Vuetify autocomplete with server-side functionality

I am looking to implement infinite pagination on the Vuetify autocomplete feature. My goal is to trigger the loading of a new page of items from the backend when I scroll to the end of the menu. Initially, I attempted using the v-intersect directive as fo ...