Adjust the prop value whenever there is a modification in the Vuex store

Following a successful mutation to the vuex store (state.posts.post.comments) with the use of this code snippet and implementing Vue.set for Vue to acknowledge the addition of an object property:

store/modules/post.js

const mutations = {
    [types.SET_POST_COMMENTS] (state, { comments, id }) {
      let post = state.posts.find(post => post._id === id)
      Vue.set(post, 'comments', comments)
    }
}

Even though the Vuex store is correctly updated with a comments object for each post, the SinglePost.vue component does not reflect these changes. The prop post is non-reactive, suggesting that even the watcher is not being triggered.

SinglePost.vue

export default {
  name: 'single-post',
  props: {
    'post': {
      type: Object
    }
  },
  data () {
    return {
      currPost: this.post // attempted to locally reassign post
    }
  },
  computed: {
    comments() {
      return this.post.comments // tried to compute comments locally
    }
  },
  watch: {
    post: function(val) { // attempted to watch currPost for changes
       console.log('never triggered')
       this.currPost = val 
    }
  }

One possible solution is to manually set a local variable by explicitly retrieving comments from the store in a component method and setting a local comments object, but I would prefer to utilize my centralized store (assuming there is a solution).

SinglePost template

{{comments}} // always empty
{{post}} // does not reflect Vue.set in the store for post.comments
{{currPost}} // does not reflect Vue.set in the store for post.comments

Edit

The method of obtaining posts is as follows:

getPosts ({ commit, state, getters, dispatch, rootState }, ctx) {
  //other stuff
  APIHelper.post('/post/search', mergedPayload).then(res => {
    var results = res.data.results
    commit('SET_POSTS', posts || [])
    // where SET_POSTS simply assigns state.posts = posts

The vuex action getPosts is triggered from the Posts.vue component without returning anything, as it is handled by a mutation @click="getPosts(this.context)" (this successfully sets the posts)

    <div v-for="post in posts">
      <single-post :key="post._id" :post="post" context="feed" />
    </div>

Answer №1

To streamline your Vuex implementation, consider utilizing the mapGetters utility function.

computed: {
    ...mapGetters({
        currentPost: 'GET_CURRENT_POST'
    })
},

This method grants access to the store state and automatically updates, eliminating the need for excess watchers or computed properties.

Answer №2

Implementing two-way data binding can boost your project's functionality. You have the option to design your own getter/setter method and integrate it into your Vue components whenever necessary:

export function bindFields(fields)
{
    let dataBindings = {}
    for (let field of fields) {
        dataBindings[field] = {
            get() {
                return this.$store.state[field];
            },
            set(value) {
                this.$store.commit(`UPDATE_${field.toUpperCase()}`, value);
            }
        }
    }
    return dataBindings;
}

To use this in your Vue component:

import {bindFields} from 'utils.js'; // or any desired file name

computed: {
   ...bindFields(['mappedData']),
},

Updating this.mappedData in your Vue component:

this.mappedData = ['apple', 'banana'];

will result in:

this.$store.commit('UPDATE_MAPPEDDATA', ['apple', 'banana']);

To access the property's data, simply call it in your component:

// In your template
{{ mappedData }}

// In Vue methods
this.mappedData;

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

Discover the specific item within an array of objects

Anyone have information like this: const info = { Title : "Banana", Quantity : 10, Location : "Everywhere", Phone : 123456, A : 987, B : 654, } and there is another array of details as: const dataArr = ["Title",&q ...

Import the complete JSON file into a variable as an array

I am struggling with loading an external json file (locations.json) into a variable and then using the information found here: http://www.json.org/js.html Despite trying various methods, I have not been successful in populating the variable. Even after fo ...

Using JavaScript to retrieve data from a JSON file and showcase it on a jQuery mobile webpage

I am struggling to retrieve JSON data from a PHP URL using JavaScript and display it within a JQuery mobile "li" tag as a category list. Despite spending the last 8 hours on it, I can't seem to get it working using the code provided below. Any help wo ...

Can you demonstrate how to incorporate a new line within a for loop?

I have an array of letters and I need to display them on the screen using a for loop. My goal is to make every sixth letter appear on a new line. Here is the code snippet: https://i.stack.imgur.com/lHFqq.jpg <script> export default { data() { ...

Is there a way to make Outlook show only the caption of a link instead of the entire URL?

In my PDF file, I have set up a button for sending an email. The email is a request that needs approval or denial. I want the recipient to respond with just 2 clicks: Click on either "Approve" or "Deny" (a new email will pop up) Click on "send" - and it& ...

Is there a way to transform a regular CommonJS declaration into an ECMAScript import when it is making multiple requires in a single line?

As a beginner in JavaScript, I am interested in converting this line into an import statement: var sass = require('gulp-sass')(require('sass')); I have successfully converted the other requires into imports but I'm struggling wit ...

"Utilize Node.js to seamlessly stream real-time Instagram photos based on a designated hashtag

Does anyone know of a node.js library or solution that can automatically fetch Instagram photos in real-time based on specific hashtags? ...

Displaying and Concealing Messages with VueJS

Currently, I have set up a basic CLI structure environment and created a component that displays messages/alerts such as "Login Failed." Since this component is intended to be reused throughout the entire app, I decided to import it into the root App.vue f ...

Is there a way to establish a connection between two excel entries using Angular?

In order to connect xlsx file records with their corresponding ids using angular, I am seeking a solution. To elaborate further: Let me provide an example for better understanding: Scenario 1 https://i.stack.imgur.com/25Uns.png Scenario 2 https://i ...

Updates to object properties are not appearing in Vue component

I am facing an issue with a Vue component that has a single prop, which is an object. Despite changing a property in this object, it does not reflect the update in the Vue template. Below is a simplified version of the component: <template> <p ...

Using Ajax and jQuery to redirect a page with values in ASP.NET

I have two pages: Default.aspx and DetailView.aspx. My goal is to redirect from Default.aspx to DetailView.aspx using an AJAX call and pass a value as well. Although I have tried something, the function defined in the class is not being called. The functi ...

Guide to generating a div element with its contents using JSON

On my webpage, there is a button that increases the "counter" value every time it's clicked. I am looking to achieve the following tasks: 1) How can I generate a json file for each div on my page like the example below: <div class="text1" id="1" ...

Musical backdrop for an online game platform

Currently, I am working on developing a game using HTML. I am trying to figure out the best way to incorporate music into the gameplay. Any suggestions on how I can add music to my web-based game? ...

Using D3-GraphViz in Javascript along with an Angular template: A step-by-step guide

I am attempting to integrate d3-graphviz following the guidance provided here within an angular template, like in this example. The tutorial on the d3-graphviz website advises me to include the following code in the index.html file: <!DOCTYPE html> & ...

extract objects from an array of objects based on a specified array

Within my JSON array, I have data structured like this: const data = [ { "uniqueId": 1233, "serviceTags": [ { "Id": 11602, "tagId": "FRRRR", "missingRequired&quo ...

Is it possible to use a Proxy-object instead of just an index when changing tabs in material-ui/Tabs?

Using material-ui tabs, I have a function component called OvertimesReport with Fixed Tabs and Full width tabs panel: const TabContainer = ({children, dir}) => ( <Typography component="div" dir={dir} style={{padding: 8 * 3}}> {children} & ...

JavaScript regular expression for detecting valid currency values

I am encountering an issue with removing decimal values from a monetary amount retrieved from a JSON feed: For example, if I have: 150,000, I want to display it as just 150 Here is the code snippet I am using: $.getJSON('/static/js/datatest.json&ap ...

Challenges encountered with input outcomes

I am facing an issue with input results. I have a button that triggers a function to check for empty input fields. However, when I click the button, it always falls into the last if statement and displays as if the fields are not empty. I have already att ...

How do I access the previous and current values in a v-for loop in Vue.js in order to compare them?

I am working on a structural component that involves looping through a list and performing certain actions based on the items: .... <template v-for="(item, INDEX) in someList"> <template v-if="thisIsArrayList(item)"> ...

Display a single specific outcome within a React component's list

import {useState, useEffect } from 'react' import axios from 'axios' const Singlecountry = ({searchedCountries, setWeather, weather}) => { const weatherName = searchedCountries[0].capital console.log(weather) useEffect(() =&g ...