Creating a dynamic `v-model` for computed properties that is dependent on the route parameter

I am creating a versatile component that can update different vuex properties based on the route parameter passed. Below is a simplified version of the code:

<template>
  <div>
    <input v-model="this[$route.params.name]"/>
  </div>
</template>

<script>
export default {
  computed: {
    foo: {
      get(){ return this.$store.state.foo; },
      set(value){ this.$store.commit('updateValue', {name:'foo', value}); }
    },
    bar: {
      get(){ return this.$store.state.bar; },
      set(value){ this.$store.commit('updateValue', {name:'bar', value}); }
    },
  }
}
</script>

Using this[$route.params.name] in the v-model makes the component dynamic and functional for setting values. However, an error occurs when trying to set a value:

Cannot set reactive property on undefined, null, or primitive value: null

It seems that this inside the v-model becomes undefined. How can this issue be resolved?

UPDATE

I am also interested in understanding why this alternative approach results in a compilation error:

<template>
  <div>
    <input v-model="getComputed()"/>
  </div>
</template>

<script>
export default {
  computed: {
    foo: {
      get(){ return this.$store.state.foo; },
      set(value){ this.$store.commit('updateValue', {name:'foo', value}); }
    },
    bar: {
      get(){ return this.$store.state.bar; },
      set(value){ this.$store.commit('updateValue', {name:'bar', value}); }
    },
  },
  methods: {
    getComputed(){
      return this[this.$route.params.name]
    }
  }
}
</script>

Answer №1

Everything enclosed within the <template> tag belongs to the scope of this, hence this remains undefined.

v-model is simply a shortcut for using :value and @input; therefore, you can address this by creating a custom event and a computed property for :value.

Alternatively, you can utilize a computed property with a getter and setter; similar to:

computed: {
  model: {
    get: function () {
      return this.$store.state[this.$route.params.name]
    },
    set: function (value) {
      this.$store.commit('updateValue', { name: this.$route.params.name, value})
    }
  }
}

Update In case you need additional logic in your setter function, it is advisable to separate it for better organization. Keep the getter straightforward and maintain a single computed property setup:

computed: {
  model: {
    get: function () {
      return this.$store.state[this.$route.params.name]
    },
    set: function (value) {
      switch(this.$route.params.name) {
        case 'foo':
          return this.foo(value)
        default:
          return this.bar(value)
      }
    }
  }
},
methods: {
  foo(val) {
    this.$store.commit(...)
  },
  bar(val) {
    this.$store.commit(...)
  }
}

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

`The steps to retrieve XML response data from an API request`

When using axios to make an API request, how can I receive data in XML format? For example: axios.get(/* URL */).then(response => {/* How do I retrieve the XML data? */}).catch(err => {/* result */}); ...

Disable the swipe feature on a Bootstrap carousel to prevent users from navigating through slides on mobile devices. The attribute data-touch="

I've been attempting to deactivate the swipe function on my Bootstrap 4 carousel in my project, but it's proven to be quite challenging. Despite it being a basic carousel, I'm finding it difficult to turn off this feature. What am I missing ...

Display or conceal a YouTube video with a click

Q1) Is it possible to use JQuery on page load to detect the file name of an image and then dynamically position it on the page with CSS? Q2) What is the most efficient way to achieve this without embedding iframe code inside a specific div.icon element? ...

Is there a method by which I can access information from a linked document in Firebase?

I am relatively new to firebase and I am attempting to retrieve data from a referenced document in another collection to display. Link 1 Link 2 This is how I add a student and the parent's ID: const newStudent = { name: req.body.name, grade: ...

What causes the button size to change in Bootstrap when switching to a spinner?

Every time I switch from a spinner back to a button, the button's size changes. I am struggling to identify the cause of this issue. function resizeButton() { var btn = document.getElementById('submitBtn'); btn.innerHTML = ' ...

Is it wise to question the validity of req.body in express.js?

https://expressjs.com/en/4x/api.html mentions It is crucial to validate all properties and values in the req.body object as they are derived from user input. Any operation performed on this object should be validated to prevent security risks. For instan ...

What is the best way to incorporate my Switch component into my Table component as a distinct column, while also maintaining separate states for each component?

My journey into learning React.js has been exciting so far. However, I am facing some confusion when it comes to stateful components. Currently, I am utilizing Bootstrap tables for creating a table and successfully fetching data using GET requests. Additio ...

What is the best way to catch an event triggered by an ElementUI tree in Vue.js?

I am utilizing the ElementUI Tree component as shown below: <el-tree :data="data" :props="defaultProps"> </el-tree> As per the documentation, a node-click event is triggered when a node is clicked. How can I se ...

Is commenting required? Well, meteor!

I am currently developing a chat application using Meteor and I am facing an issue where I want to require users to type something before sending a message (to prevent spamming by hitting enter multiple times). Unfortunately, I am unsure of how to achieve ...

How to overcome the issue of Vue.js mobile router-link being blocked by v-on:mouseover

Here is a for list snippet: <li class="projects-item" v-for="project in filteredProjects" :key="project.id" v-on:mouseover="displayHoverInfo($event, project)" v-on:mouseleave="hover = false" > <router-link v-bind:to="'/project/ ...

Angular Promise not executing in a synchronous manner

In the javascript controller, I have a code snippet that consists of two separate functions. While these functions work individually and asynchronously when triggered from the view, my goal is to execute them synchronously on page load. This is necessary b ...

How about: "Using Node.js and Express to declaratively define a route for

I am facing an issue managing my routes in declarative objects and initializing/registering the endpoint handlers using one or more of these objects. The problem arises when I attempt to register the handlers in a loop of the declarative routes, methods, ...

JavaScript code for validating two passwords is malfunctioning

I'm currently working on a registration form for my website and I'm trying to implement a JS script that compares two password inputs (password and repeat password) and displays a message saying "passwords are not the same." Below is the code I h ...

What is the process for applying a border to the chosen image within the ImageList of the MaterialUI component?

Currently, I have set up the images in a grid format using the and components from MaterialUI. However, I am looking to implement an additional feature where when a user clicks on a specific image from the grid, a border is displayed around that select ...

What is the best way to format or delete text enclosed in quotation marks within an anchor tag using CSS or JavaScript?

I have encountered an issue with a dynamically generated login form. When I select the 'Forgot Password' option, a new 'Back to Login' message appears along with a separating '|' line. Removing this line is proving challenging ...

Acquiring a fresh scope in Angular via a different component

In my project, I am developing an app using a component-based approach with Angular 1.5.5. As part of this development, I am utilizing d3js to create some elements with the class .floating-node. For each of these nodes, I am creating a new $scope and appe ...

Issues with integrating the jsPDF package into a JavaScript project

I'm struggling to solve this issue. I've been attempting to create a program that can download a pdf from a webpage using the jsPDF npm module. After downloading it, I tried importing it in two different ways: Using the node.js require statemen ...

Using React and Redux to update the state of an object with the current state

Upon mounting my component, I make a call to an API and upon success, the state is updated with the following data: { "brief":"No brief given", "tasks":[ { "_id":"5c74ffc257a059094cf8f3c2", " ...

When waiting for proxy leads to access the 'then' property, what should be my next move?

In my code, I am using a special Proxy to imitate a virtual object. The getter of this proxy returns values that are already prepared. After some exploration, I found out that when the proxy is awaited, it triggers the 'then' property of the pro ...

Tips for handling imports and dependencies in a React component that is shared through npm

Hello everyone, I'm diving into the world of sharing React components and have encountered an interesting challenge that I hope you can help me with. Currently, I have a button component in my app that is responsible for changing the language. My app ...