Manipulate and synchronize state in Vue using vuex from a separate component

Imagine this scenario: I have two files - App.vue and Home.vue. In App.vue, there is a navigation drawer component, and in Home.vue, there is a toolbar component. The issue arises when I try to toggle the state of the navigation drawer (true or false) from the toolbar component in Home.vue (where the navigation drawer is rendered). Surprisingly, the code snippet below does not produce any errors but fails to change the visibility of the navigation drawer. Strangely enough, manually setting the state in store.js does reflect the changes in the navigation drawer. Can someone enlighten me with a solution?

store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    drawer: false
  },
  mutations: {
    toggleDrawer: function(state) {
      return state.drawer = !state.drawer;
    }
  },
  actions: {
    toggleDrawer({ commit }) {
      commit('toggleDrawer');
    }
  },
  getters: {
    active: (state) => {
      return state.drawer;
    }
  }
})

App.vue

<v-navigation-drawer v-model="drawer"> ... </v-navigation-drawer>

<script>
  import store from './store'
    export default {
      data: function() {
        return {
          drawer: this.$store.state.drawer
        }
      }
    }
</script>

Home.vue

<v-toolbar-side-icon @click="$store.commit('toggleDrawer')"> ... </v-toolbar-side-icon>

<script>
  import store from '../store'
  export default {
    data: function() {
        return {
          drawer: this.$store.state.drawer // Maybe unnecessary here
        }
    }
  }
</script>

Answer №1

This post may be a bit dated, but for anyone seeking the solution, it appears to do the trick.

Referencing the Form Handling section of the Vuex guide, specifically the Two-way Computed Property

I made some adjustments to the codesandbox provided by Sovalina (thanks!) available at this link

Another option is utilizing v-model

<v-navigation-drawer v-model="drawer" app>

by implementing the two way computed property instead of using mapGetters

<script>
    export default {
        computed: {
            drawer: {
                get () {
                    return this.$store.state.drawer
                },
                set (value) {
                    this.$store.commit('toggleDrawer', value)
                }
            }
        }
    }
</script>

Answer №2

If you want to avoid mutating your store outside of Vuex, consider using the navigation drawer's permanent property instead of v-model. Also, make sure to utilize the getter active that you have defined.

In your App.vue file:

<template>
  <v-app >
    <v-navigation-drawer :permanent="active">
      ...
    </v-navigation-drawer>
  </v-app>
</template>

<script>
  import { mapGetters } from 'vuex'
  export default {
    computed: {
      ...mapGetters([
        'active'
      ])
    },
  }
</script>

For Home.vue:

<template>
  <v-toolbar-side-icon @click="toggle"> ... </v-toolbar-side-icon>
</template>

<script>
  export default {
    methods: {
      toggle() {
        this.$store.dispatch('toggleDrawer')
      }
    }
  }
</script>

Note: Since you have an action called toggleDrawer in your store, it is recommended to use dispatch instead of commit.

Check out the live example here

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

Challenge with Filter Functionality when Activating Button

Can you help me implement a search filter using buttons with the Isotope Plugin? For example, entering a search value in an input field and then clicking a search button to display the search results. How can I achieve this using buttons? Below is the H ...

Issue with loading Bootstrap modal in KnockoutJS

Currently, I am working on a project to develop a CRUD system using knockoutJS and fetching data through an AJAX call. While I am still in the process of implementing the add and delete functionalities, I am facing issues with my modal. The modal form does ...

Understanding how to display a component within another component in Vue.js

I am faced with a scenario where I have a component that has the following template: <div v-for:"item in store" v-bind:key="item.type"> <a>{{item.type}}</a> </div> Additionally, I have another component named 'StoreCompone ...

What is the best way to send an ID to my ui-view component?

I am trying to access inventory items by their ID using the link /inventory/description/:{{id}}. However, I am facing some issues with it as nothing is showing up. How can I successfully access these items by ID? app.config(function config( $stateProvider ...

Best practices for creating a ColdFusion service for transmitting JSON data and receiving it through AngularJS

I've been facing a tough situation working all day :(. Any help would be greatly appreciated. My website needs to use the $http provider to call a ColdFusion file from another domain. Let's assume the link to the cfm file is: http://xample.com/g ...

I attempted to connect my JavaScript file to my HTML file, but unfortunately, no changes are taking place

I have created an HTML file where I am trying to pass input from it into a function located in a separate JavaScript file, and then have the data added to a SQL server. The JavaScript file works perfectly fine when run independently, but when I try to call ...

Error: The function was expecting a mapDiv with the type of Element, but instead undefined was passed - google

I have a map within a div tagged with #mapa. Whenever I try to plot a route on the map, it refreshes. I don't want the map to refresh, and here is the code I currently have: <div style="height: 500px; width: auto;" #mapa> <google-map heigh ...

JavaScript eliminates any existing CSS styling

I am new to the world of web development and recently created a sample webpage. The page consists of an HTML file, a CSS file, and a JavaScript file. However, I encountered an issue where linking the JavaScript file to the HTML page caused the CSS formatti ...

What is the best way to consistently resolve URLs in relation to the root of my web application?

My web application includes a JavaScript file with the following line of code: var arrowimages = { down: ['downarrowclass', 'images/AppNavDownArrow.gif', 23], right: ['rightarrowclass', 'images/AppNavRightArrow.gif' ...

Can we establish communication between the backend and frontend in React JS by utilizing localstorage?

Trying to implement affiliate functionality on my eCommerce platform. The idea is that users who generate links will receive a commission if someone makes a purchase through those links. However, the challenge I'm facing is that I can't store the ...

The getelementbyid function is unable to locate the specified button identifier

As I dive into the world of Javascript, I wanted to create a simple input form with a corresponding response field on my website. However, I encountered an issue where using a basic submit button caused the page to refresh and erase the textfields before ...

The $route object in vue-router appears to be empty when used with single file components

I am facing an issue while using single file components with vue-router and vue-2.0. The problem I can't seem to resolve is that the this.$route object, when called from a component, always returns empty values. For example: https://i.sstatic.net/ws ...

What is the method for retrieving array values from an attribute?

I am currently developing an Angular 6 application and I need to pass and retrieve array values dynamically through attributes. Here is the code snippet I have used for this purpose: HTML: <ul class="list-unstyled" id="list" [attr.parent_id]="123"> ...

Enhancing Accessibility for the jQuery Countdown Plugin

Seeking to enhance the accessibility of my website's jQuery countdown, I am striving to adhere to WAI-ARIA guidelines. The specified requirements are as follows: Ensure the area is live so it updates dynamically with the countdown display. Avoid re ...

The fetch function in my Node.js code is failing to properly display JSON data from a file on the console

I am currently exploring node.js and working on building a web server to fetch a list of team members from a JSON file in the 'json' folder. However, I am encountering an issue with my fetch function as it is not displaying the data on the consol ...

What is the best way to enable click functionality on the SVG Object and smoothly scroll to anchor using jQuery?

My SVG is embedded using an object tag and includes CSS3 hover animations. However, I am facing issues when trying to hyperlink the SVG with hover animation as it interferes with clicking actions. I chose not to use the long SVG path code for better code o ...

Tutorial on incorporating Font Awesome icon into tab view within the Nativescript Vue environment

I'm attempting to incorporate a font-awesome icon within a TabView item. While I have successfully used this code elsewhere on the page with no issues, the icon does not display within the tabview. Here's my setup in main.js: import {TNSFontIco ...

Retrieve postal code using longitude and latitude data from Google's API

I am currently working on a project that requires obtaining a postcode from longitude and latitude coordinates. Utilizing the Google Maps API, I'm able to retrieve the longitude and latitude based on a search term like 'Manchester'. After t ...

Changing both image border and text at the same time when hovering- how can this be done

I have taken on the challenge of creating a Netflix Clone as a personal project. In my version, I want the border around the image and the user's name to both highlight when hovered over in the Netflix Profiles section. However, despite trying for o ...

Leveraging various libraries in React

My query revolves around a React application where I have integrated Material UI for only two components. Despite installing the entire Material UI library, will this lead to an increased bundle size for my application? Or does the build process only inc ...