Home > Net >  How to target the dom of element of other component by vue
How to target the dom of element of other component by vue

Time:10-24

By clicking on the icon: (Sidebar.vue)

<i class='bx bx-menu' v-on:click="toggleMenu()" id="btn"></i>

I would like to toggle the classes of the elements that are in another components:

methods: {
            toggleMenu() {
    document.querySelector(".header").classList.toggle("changeWidth");
    document.querySelector(".footer").classList.toggle("changeWidth");
    document.querySelector("#app-content").classList.toggle("addOpacity");
    document.querySelector(".main-content").classList.toggle("main-content_move-left");
            }
         }

Can I do it in another way using Vue instruments?

CodePudding user response:

The main idea is to use a framework like Vue is manage the state of your application, I think you are following an old path trying to target the DOM elements and the idea is verify the reactive changes that you have in your app

I recommend to you read more about Vue and how works but a basic idea is:

Parent to child communication:

In this type of communication, a parent passes the data to the child by adding an argument in the component declaration. Those are called props

<template>
  <div>
    <Car color="green" />
  </div>
</template>

Props are one-way: from parent to child. Any time the parent changes the prop, the new value is sent to the child and rerendered.

The reverse is not true, and you should never mutate a prop inside the child component.

Child to parent communication

In this type of communication, Events ensure communication from child to parent.

<script>
export default {
  name: 'Car',
  methods: {
    handleClick: function() {
      this.$emit('clickedSomething')
    }
  }
}
</script>

The parent can intercept this using the v-on directive when including the component in its template:

<template>
  <div>
    <Car v-on:clickedSomething="handleClickInParent" />
    <!-- or -->
    <Car @clickedSomething="handleClickInParent" />
  </div>
</template>

<script>
export default {
  name: 'App',
  methods: {
    handleClickInParent: function() {
      //...
    }
  }
}
</script>

So following that concept you will be able to render your components based on certain values for example using v-if directive

<h1 v-if="showHeader">Show your header</h1>
<h1 v-else>Show something else</h1>

Following this idea, you will be able to toggle elements whatever that you want

  • Related