Configuring Vuex State

Currently, I have a prop that is being bound to a child component. My goal is to eliminate this binding and instead assign the value to a data property in a vuex global state.

<VideoPip :asset="asset" v-show="pipEnabled === true" />

I am wondering how I can assign this.$store.state.assetVideo;, which is initially an empty object, to the asset value. Should I do this within a computed property?

Answer №1

To access the video state data, simply utilize the mapState helper. Here's an example implementation in your Video component:

import { mapState } from 'vuex'

export default {
  name: 'Video',
  computed: mapState(['assetVideo'])
}

You can then use this.assetVideo within your component's methods and assetVideo in its template. This setup will reactively update based on changes in the store.


When it comes to setting the value, mutations are essential. Here is a basic example of how you can define a mutation:

const store = new Vuex.Store({
  strict: true,
  state: {
    assetVideo: {}
  },
  mutations: {
    setVideoAsset: (state, assetVideo) => (state.assetVideo = assetVideo)
  }
}

Then, in your components, you can trigger this mutation like so:

methods: {
  selectVideo (video) {
    this.$store.commit('setVideoAsset', video)
  }
}

Answer №2

To implement this in your parent component:

// if you do not use a namespace
import { mapMutations, mapState } from 'vuex'

export default {
  computed: {
    ...mapState(['assetVideo']),
    asset: {
      get() {
        return this.assetVideo
      },
      set(newValue) {
        this.setAssetVideo(newValue)
      }
    }
  },
  methods: {
    ...mapMutations(['setAssetVideo']),
  }
}

Store setup:

const store = {
  state: {
    assetVideo: {}
  },
  mutations: {
    setAssetVideo(state, payload) {
      state.assetVideo = payload
    }
  }
}

In the parent component, you can update the state using this.asset = 'something' and it will reflect changes in the store and any other components utilizing it.

You can also pass this data to child components easily.

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

Displaying the getJSON output only once, then having it automatically update at regular intervals without any repetitive results

I previously had an issue resolved on stackoverflow, but the requirements of my project have changed. Therefore, I am in need of a new solution. In summary, I have a getJSON function that runs every 5 seconds to check for changes in a JSON file. The proble ...

Is there a built-in method or library for extracting data from JSON strings in programming languages?

Duplicate Query: how to parse json in javascript The data sent back by my server is in JSON format, but it doesn't follow the usual key/value pairs structure. Here's an example of the data I'm receiving: ["Value1","Value2","Value3"] ...

Located at the lower section of the parent container

In my flex container, I have two boxes arranged side by side (collapsing into one column on smaller screens). I've ensured that these boxes have the same height when displayed together, as shown in the image below: Now, my goal is to position the ED ...

Please input a number that falls within a specified range

I need help with two text inputs that are connected v-model to a ref object. I also have two other refs, minimum (100) and maximum(1000). My goal is to allow users to input values within the range of the minimum and maximum values provided. If the value en ...

``There seems to be an issue with the recognition of Vue.js, VSCode, Vetur, Emm

Currently utilizing Vue.js on VSCode with Vetur installed for formatting. Despite watching a video tutorial that mentioned Scaffold snippets and Emmett code completion should be available, I cannot seem to locate them on my VSCode. When attempting to typ ...

Could not locate module: Issue: Unable to resolve './Firebase'

I'm a beginner with React and I've been working on setting up Firebase in my React application. import firebase from 'firebase/compat/app'; import 'firebase/compat/auth'; import 'firebase/compat/firestore'; var fire ...

Re-rendering an array in Vue.js with sorted elements

I am working on a basic sorting user interface to sort comments based on certain values: Within the CommentsSection template: <div v-if="numComments" class="tabs d-flex"> <span class="text-muted">Sort by:</span> <div cl ...

Is there a problem with `window.google` being undefined in a React

Every time I call window and use console log, a google prop appears as shown below: https://i.sstatic.net/dSMs8.png But then when I attempt to call window.google, it returns undefined. Am I overlooking something here? ...

What is the process for initiating printing in a separate window?

Is there a way to modify the code below so that when I click "Print" it opens in a new window instead of redirecting and losing the original receipt? <div class="print_img"> <button onclick="myFunction()"> <div align="justify ...

retrieving the parent of the a tag from a jquery form

When using the jQuery code below: $('#trade-offer form').on("submit", function(event) { event.preventDefault(); var stock = $(this).closest('.allloopedover'); console.log(stock); return; $.ajax({ url: ajaxur ...

Next.js (TypeScript) - Error: Property 'req' is not recognized on the type 'GetServerSideProps'

Currently, I am tackling a challenge involving the utilization of next-auth and attempting to access the session from within getServerSideProps. However, in order to achieve this, it is essential for me to provide the context request and context response ...

The placeholder attribute for input types does not display consistently across all browsers

I am experiencing an issue with the placeholder text in my input field. <input type="text" name='linkLabel{{index}}' autocomplete="off" class="input-large tight-form-url last remove-cross" required="required" placeholder="{{'linkLabel&ap ...

Using AngularJS, generate a JSON array with a specified key

Looking to create a JSON array structure with keys using AngularJS, but unsure how to push data in order to achieve this. The goal is to generate a JSON array based on the provided data below. $scope.category = [{"id": 20, "name": "vegetable"}, {"id": ...

Encountering an issue with Server Side Rendering in React Router Dom where an error message pops up saying: "Warning: React.createElement: type is

Specific Error: A warning has occurred: React.createElement: the type provided is invalid -- it was expecting a string (for built-in components) or a class/function (for composite components), but instead received an object. in Posts in Connect(Po ...

Converting SVG to PNG image directly in the browser (compatible with all browsers, including Internet Explorer)

I am currently working with Highcharts and I have a need to convert all the charts displayed on the webpage into images so that I can send them to my server for merging with a master export Excel file. The Excel file already contains some tables and pivot ...

Issue encountered with create-next-app during server launch

Encountering an error when attempting to boot immediately after using create-next-app. Opted for typescript with eslint, but still facing issues. Attempted without typescript, updated create-next-app, and reinstalled dependencies - unfortunately, the prob ...

Sharing configurations between a Node.js application and client-side JavaScript

I am facing an issue where I need to use a config object in both my node app and browser. Below is the path and content of the configuration file: path: [app]/public/js/config.js content: var config = { "foo": "bar", "num": 42, "list": ["a" ...

Discovering the significance of a function's scope

I'm a bit confused about how the answer is coming out to be 15 in this scenario. I do understand that the function scope of doSomething involves calling doSomethingElse, but my calculation isn't leading me to the same result as 15. function doSo ...

What is the correct method for configuring access permissions?

I'm in the process of developing a user management system, but I keep finding myself having to check the user type for each router. router.get('/admin/settings', (req, res) => { if(admin) { //Proceed. } } router.get(&apo ...

Implementing dynamic components in Vuejs by passing props from objects

I have developed a dashboard application that allows users to customize their dashboard by adding widgets in any order. While the functionality is working fine, I am looking to address some technical debt and clean up the code. Let's simplify things ...