Utilizing Vue.js: Dynamically linking v-model to route parameters depending on the current state

I'm currently in the process of developing an application that will serve as the backbone for a restaurant chain's website. The main functionality involves allowing users to modify page content and images. Given the complexity of the site with its numerous nested pages and sections, I've opted against hardcoding templates for each specific page or section edit. Instead, my approach is centered around creating a standardized template that can accommodate edits for all pages based on data retrieved from the route.

My current hurdle lies in implementing the v-model for my text input field.

Below is a snippet of my router code:

{
          path: '/dashboard/:id/sections/:section',
          name: 'section',
          component: () => import('../views/Dashboard/Restaurants/Restaurant/Sections/Section.vue'),
          meta: {
            requiresAuth: true
          },
        },

Within my Section.vue file, you'll find the following segment containing the text input field equipped with a v-model attribute. In this instance, I'm focusing on editing the "Welcome" section of a restaurant. While it would function flawlessly if designed solely for editing the Welcome text, the challenge arises when dealing with approximately 40 different sections:

<vue-editor v-model="restInfo.welcome" placeholder="Update Text"></vue-editor>

The issue at hand involves dynamically referencing the "welcome" portion within the v-model. Considering the need to address a myriad of Sections, it becomes essential to update the v-model based on the route parameters for seamless functionality. Though attempting to use v-model="restInfo. + section" proves ineffective.

Is there any viable solution to adjusting the v-model based on the specifics outlined in the route parameters?

Thank you in advance!

Additional Information...

Feel free to peruse through my comprehensive Section.vue below:

<template>
  <div>
    <Breadcrumbs :items="crumbs" />
  
    <div v-if="restInfo">
      <h3>Update {{section}}</h3>
      <div class="flex flex-wrap">
        <div class="form__content">
            <form @submit.prevent>
            <vue-editor v-model="restInfo.welcome" placeholder="Update Text"></vue-editor>
            <div class="flex">
                  <button class="btn btn__primary mb-3" @click="editText()">
                    Update
                    <transition name="fade">
                      <span class="ml-2" v-if="performingRequest">
                      <i class="fa fa-spinner fa-spin"></i>
                      </span>
                    </transition>
                  </button>
                </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>



<script>
import { mapState } from 'vuex'
import { VueEditor } from "vue2-editor"
import Loader from '@/components/Loader.vue'
import Breadcrumbs from '@/components/Breadcrumbs.vue'

export default {
  data() {
    return {
      performingRequest: false,
    }
  },
  created () {
    this.$store.dispatch("getRestFromId", this.$route.params.id);
  },
  computed: {
    ...mapState(['currentUser', 'restInfo']),
    section() {
      return this.$route.params.section
    },
    identifier() {
      return this.restInfo.id
    },
    model() {
      return this.restInfo.id + `.` + this.section
    },
    crumbs () {
      if (this.restInfo) {
        let rest = this.restInfo
        let crumbsArray = []
        let step1 = { title: "Dashboard", to: { name: "dashboard"}}
        let step2 = { title: rest.name, to: { name: "resthome"}}
        let step3 = { title: 'Page Sections', to: { name: 'restsections'}}
        let step4 = { title: this.$route.params.section, to: false}
        crumbsArray.push(step1)
        crumbsArray.push(step2)
        crumbsArray.push(step3)
        crumbsArray.push(step4)
        return crumbsArray
      } else {
        return []
      }
    },
  },
  methods: {
    editText() {
      this.performingRequest = true
      this.$store.dispatch("updateRest", {
        id: this.rest.id,
        content: this.rest
      });
      setTimeout(() => {
        this.performingRequest = false
      }, 2000)
    }
  },
  components: {
    Loader,
    VueEditor,
    Breadcrumbs
  },
  beforeDestroy(){
    this.performingRequest = false
    delete this.performingRequest
  }
}
</script>

Answer №1

Consider utilizing the square brackets accessor [] in place of the dot operator .:

<vue-input v-model="userData[info]"

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

Connecting prop variables to component variables establishes a direct relationship between them

By assigning the props variable to a component variable, any changes made to the component variable will also reflect in the props... Parent Component: const prova = [ { 1: 'a' }, { 2: 'b' }, { ...

Is it possible for two components to send two distinct props to a single component in a React application?

I recently encountered a scenario where I needed to pass a variable value to a Component that already has props for a different purpose. The challenge here is, can two separate components send different props to the same component? Alternatively, is it po ...

Having trouble with jQuery variable assignments not working in Safari?

My jQuery 1.3.2 code is encountering issues with Safari 4 for reasons unknown to me. Even though all my javascript references are placed right before the closing <body> tag, I am facing difficulties with the following snippet: var status = $(' ...

Different ways to eliminate unnecessary items in an array

One task I have is to eliminate all duplicate elements within an array, as shown in the example below: var arr = [ {'seriesIndex':1,pointIndex:0}, {'seriesIndex':1,pointIndex:1}, {'seriesIndex':0,pointIndex:0}, ...

What is the best way to partition JSON data from an API request in React and display it in various sections within the component

There are 2 JSON objects that contain sales period details based on Month to date and year to date. The data includes information such as Units Sold, Gross Revenue, Year to Date Totals, Month to Date Averages, Expenses, Net Revenues, and Per Unit values. I ...

Ways to thwart CSRF attacks?

I am currently looking for ways to protect my API from CSRF attacks in my Express app using Node.js. Despite searching on both Google and YouTube, I have been unable to find a solution that works for me. One tutorial I watched on YouTube recommended gene ...

Using Vue.js and Laravel to send requests using Axios

In my Vue.js code, I have a method that uses axios to send a PUT/CREATE request to my Laravel API's create method and passes some data along with it. create(data) { this.mute = true; window.axios.put('/api/showreels/create', {data}) ...

Is there a way to preserve all the downloaded node modules in the package.json file?

Is there a way to keep track of all the node modules installed in package.json without the need for reinstalling them? I've heard about running npm init --yes, but I'm not entirely convinced if that will do the trick. Any assistance on this mat ...

endless cycle when utilizing useEffect with a mandatory function

I'm currently in the process of creating a custom hook for sorting and filtering tables within a dashboard application. However, I am encountering an issue with an infinite loop when attempting to refetch data after changing sort or filter fields. The ...

Tips for incorporating an HTML file using ng-include in double curly brace syntax {{ }}

Here is the code snippet I am working with: <div ng-repeat="pTabs in child.productTabs" ng-click="toggleProductTab($index)" ng-if="productTabIsActive(pTabs, $index)"> <div ng-repeat="specs in pTab.additionalSpecs"> <p>{{spec ...

Insert text within the switch component using Material-UI

Looking to customize Material UI's Switch component with text inside? Check out the image below for an idea of what I'm going for. https://i.stack.imgur.com/KadRZ.png Take a look at my code snippet: import React from 'react'; import S ...

Discovering the version of the Javascript library utilized on a website - a step-by-step guide

My quest is to uncover the versions of JavaScript libraries being utilized by popular websites. By using phantomjs.exe, I successfully identified the version information for jquery. However, I am currently at a loss on how to expand this capability to inc ...

rearrangement of characters in a string (javascript)

I am currently working on a game where users have to guess a word by selecting the right symbol from the alphabet. When the user guesses correctly, the code is supposed to replace all placeholders with the correct character, but in the wrong order. var se ...

At what point should you invoke db.close() while utilizing cursor.forEach()?

When working with .toArray(), it is common practice to include db.close() within the callback function. For example: db.collection('grades').find(query).toArray(function(err, docs) { if (err) throw err; console.dir(docs); db.close(); }); ...

Trouble with feedback form not showing up

I've been working on creating an ajax feedback form, but I'm facing difficulties in getting it to show up properly. The feedback image appears, but clicking on it doesn't trigger any action. Here's my Form: <div id="feedback"> ...

Enhance your image viewing experience with a React component that smoothly zooms in on images without distorting their dimensions, all with

After searching extensively for a solution, I have been unable to find one that works. My current setup involves using React with Bootstrap. I am in need of a stateless functional component that can take an image path as input and return an img element. Th ...

Choosing Vue select options depending on a condition

I am working on a dropdown template with Vue.js and have encountered some challenges. Here is the basic structure of my dropdown: <select v-model="selectedClient" class="stat-select text-u-c"> <option disabled value="">Please select a Client ...

Is there a way to dynamically compute the height of rows in a VariableSizeList based on their index?

Is there a method to dynamically calculate the height of rows in React using the react-window library? Since it's uncertain whether all rows will have the same size, I find myself needing to utilize VariableSizeList. However, I'm wondering if the ...

Why do we need to use [`expression`] notation?

I've recently started exploring reactjs and I came across this code snippet: handleChange = event => { const { name, value } = event.target this.setState({ [name]: value, }) } I'm a bit puzzled about the notation used here: [name ...