I found myself unable to alter the vuex state

My goal is to update the state based on user input. For example, if the user types "green" in the input form, I want the state to change to green. However, when I tried to debug the input word using the Vue debugger in Chrome, I couldn't see any changes in the state.

I also encountered a mutation type error after inputting 'green', 'red', and 'blue'. I made some changes to the import part in the main.js file:

import store from './store'
import {store} from ./store” // After making this change, the error disappeared but the state did not change.

Main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import {store} from './store'

Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

App.vue

<template>
  <div id="app">
    <router-view/>
  </div>
</template>

<style lang="scss">
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

#nav {
  padding: 30px;

  a {
    font-weight: bold;
    color: #2c3e50;

    &.router-link-exact-active {
      color: #42b983;
    }
  }
}
</style>

Home.vue

<template>
  <div class="home">
    <input v-model="message" placeholder="green red blue">
    <p>Color: {{ message }}</p>
  </div>
</template>

<script>
// @ is an alias to /src


export default {
  name: 'Home',
  data(){
    return {
       message: 'Color' 
    }
  },
  watch: {
    message: function(newMessage){
       console.log(newMessage)
       if(newMessage=='green'){
          this.$store.dispatch('changeColor', newMessage)
       } else if(newMessage=='red') {
          this.$store.dispatch('changeColor', newMessage)
       } else if(newMessage=='blue') {
          this.$store.dispatch('changeColor', newMessage)
       }
    }
  },
  components: {
    
  },
  method: {

  }
}
</script>

index.js from store

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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    color: null
  },
  mutations: {
    setColor(state, color) {
      state.color = color
    }
  },
  actions: {
    changeColor({commit}, color) {
      console.log(color + 'action')
      commit('setcolor', color)
    }
  },
  getters: {
    getColor(){
      return this.$state.color;
    }
  },
  modules: {
  }
})

Answer №1

To utilize

import {store} from './store'

You must first define your store in main.js like this.

const store = new Vuex.Store({

// store code goes here

}}

export default {store}


Alternatively:

import store from './store'

const store = new Vuex.Store({

// store code goes here

}}

export default store


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

AngularJS offers the same features as Dev HTTP Client for similar functionality

Currently, I am developing a web interface using AngularJS. My goal is to achieve similar functionality as the Dev HTTP Client, but I am struggling with adding headers the way DHC does. I have attempted to implement it like this, but it's not working ...

Customize Bottom Navigation Bar in React Navigation based on User Roles

Is it possible to dynamically hide an item in the react-navigation bottom navigation bar based on a specific condition? For example, if this.state.show == true This is what I've attempted so far: const Main = createBottomTabNavigator( { Home: { ...

Is it possible to effortlessly update all fields in a mongoose document automatically?

Take for instance the scenario where I need to update a mongoose document in a put request. The code template typically looks like this: app.put('/update', async(req,res) => { try{ const product = await Product.findById(req.body.id) ...

Sliding out the sidebar menu with Jquery

Hey there! I'm currently working on implementing a swipe feature for the side menu bar. I have already added a click method in my code, but now I also need to incorporate a swipe technique. When the side bar is opened, I want to remove the inside im ...

After Vue 3 <router-view> was built in history mode, it received comments

My Vue project works perfectly in hash router mode, but when I switch to history mode, only the navbar is displayed and the <router-view> is commented out. I have already configured my apache settings for history mode. router.js import { createRoute ...

The breakdown in communication between node and mysql has caused a disruption

I've established a connection between Node and MySQL using an external database: const dbConnection = mysql.createConnection({ host: '178.129.145.252', port: 3306, user: '', password: '', database: '*****' }) ...

Angular JS allows for the display of text from a textarea upon clicking the submit button

Q] How can I display a single text message from a textarea upon clicking the submit button in angular-js? Here is the current code that I have: <html ng-app="myApp"> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1 ...

Removing HTML DOM elements from a string using JavaScript: A step-by-step guide

Hey there, I'm currently working on my angular application. When it comes to inserting the first 100 characters of content into the "description" meta tag for Facebook sharing, I've run into an issue. The description ends up including the HTML el ...

Error: An anomaly token was encountered while deploying a Laravel/Vue project using the pipeline yml in Yarn Run

I have encountered a challenge while trying to deploy my project to a server using bitbucket-pipeline with a .yml script. The project consists of a Laravel backend with PHP 7.4 and a Vue Js frontend. The issue arises during the frontend build process with ...

After the php array has been json_encoded, what should be my next step?

Exploring the realms of PHP and JavaScript is new to me, and I'm encountering difficulty in finding a way for them to communicate effectively. After converting a PHP array into JSON using json_encode(), I feel unsure about the next steps. Despite sear ...

Tips for updating a Laravel project following modifications to a JavaScript file and controller

After adding a .blade.php file and making changes to a controller and javascript file in my Laravel project, I am unable to see the updates on the server (localhost). Is there a specific command I need to use to refresh or update the project? ...

Double-triggered Jquery event

I am currently exploring Jquery and conducting some experiments. Here is the code I'm working with: <div id="wrapper"> <p id="success"></p> <h1>Break the views</h1><br> <img id ="product" src="Tshirt ...

Deactivate every textarea within a loop when adding a comment to a post using Vue.js

How can I modify my code so that only one text area opens at a time when I click the comment button instead of all text areas opening simultaneously? // Sample View <div id="app" v-cloak> <div v-for="post ,key in posts" > @{{post.content ...

React - z-index issue persists

My React App with Autocomplete feature is almost complete, but I need some assistance to double-check my code. https://i.stack.imgur.com/dhmck.png In the code snippet below, I have added a search box with the className "autocomplete" style. The issue I a ...

What is the process for retrieving the data transmitted via Jquery.getJSON on the server side?

This is the $.getJSON call I'm using on the client side: $.getJSON('/video/getToken', {classroomId: roomName}, cb); And this is what I have on the server side: router.route('/video/getToken') .get(function(req, res) { ...

What is the best way to simulate DynamoDB promise functionality with Jest?

Looking for a solution without using any libraries (as they haven't worked in my case). How can I make it work for that promise returned by the dynamodb query? Check out the code to be tested below: const isUrl = require('is-url'); const ...

What is the best way to handle a global variable in Vue.js?

I am facing an issue with a mobile webview where a global config object is being injected: Vue.prototype.$configServer = { MODE: "DEBUG", isMobile: false, injected: false, version: -1, title:"App", user: null, host: "http://127.0.0.1:8080" } ...

The NodeJS application experiences a crash if incorrect parameters are provided to the API

Currently, I have built a CRUD API using TypeScript with Node.js, Express, and MongoDB. My goal is to ensure that the API functions correctly when the correct parameters are sent through a POST request. However, if incorrect parameters are passed, the Node ...

This JavaScript operates in solitude, unable to collaborate with other JavaScripts

I received this code from an outsourced programmer: <script type="text/javascript"> $(function(){ $('#notif-icons > li > a, #top-menu > li > a').click(function() { var clicked = $(this).next('.popup-notif&a ...

An alternative way to adjust font size without having control over the HTML code

Is there a way to adjust the font size in a web page when only the div or iFrame is editable, not the actual HTML content? Our website allows users to upload their own ebooks, resulting in uncontrolled and complex HTML content for each chapter. We want to ...