Difficulty in transferring form fields across components within a form at a higher level

Just starting out with Vue and I need to develop a tiered select field form. This means that the option selected in A will determine the options for B, which in turn determines the options for C.

I'm still learning frontend frameworks so this might not be the best design approach. However, not every instance of A (SelectState.vue) in a view requires all the children, so I wanted to make them modular.

Currently, I have a top-level component displaying the select options:

SelectState.vue

<template>
  <div id="select-state">
    <span>{{ label }}</span>
    <select v-model="selectedState">
      <option v-for="state in states" :key="state">
        {{ state }}
      </option>
    </select>
  </div>
</template>

<script>
export default {
  name: 'select-state',
  data() {
    return {
      selectedState: '',
      states: ['TX']
    };
  },
  props: ['label']
  // this.states = axios.get('xxx')
}
</script>

Index.vue

<template>
  <div id="form">
    <v-select-state label="State"></v-select-state>
    <v-select-zip label="Zip"></v-select-zip>
  </div>
</template>

<script>
import SelectState from './SelectState.vue'
import SelectZip from './SelectZip.vue'

export default {
  name: 'Index',
  components: {
    'v-select-state': SelectState,
    'v-select-Zip': SelectZip
  }
}
</script>

Then, I have a SelectZip.vue which is similar to SelectState.vue, except it requires a parameter in its

axios.get('XXX', params = {'state': ???})
. But I'm struggling to figure out how to pass that necessary parameter.

Thank you in advance!

Edit: Combined with @dziraf's answer, my working albeit lengthy SelectedZip.vue looks like this:

<template>
  <div id="select_zip">
    <span>{{ label }}</span>
    <select v-model="selected_zip">
      <option v-for="zip in zips" :key="zip">
        {{ zip }}
      </option>
    </select>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'select_zip',
  data() {
    return {
      zips: []
    };
  },
  props: ['label'],
  computed: {
    selected_zip: {
      get () { return this.$store.state.formModule.zip },
      set (value) { this.$store.commit('formModule/setZips', value) }
    },
    selected_state: {
      get () { return this.$store.state.formModule.state }
    }
  },
  methods: {
    getValidZips(state) {
      axios.post('/api/v1/get_valid_zips', {
        params:{'state': state }})
        .then(response => {
          this.zips = response.data
        })
        .catch(error => {
          console.log(error)
        })
    }
  },
  watch: {
    selected_state(value) {
      this.getValidZips(value)
    }
  }
}
</script>

Answer №1

To pass data in your select components from the main form component, you can add 'state' props, although this may not be a sustainable solution in the long run.

Instead, consider utilizing Vuex. Here's an example configuration:

@/store/modules/form.js

const Form = {
  namespaced: true,
  state: {
    state: '',
    zip: ''
  },
  getters: {},
  mutations: {
    setState (state, payload) {
      state.state = payload
    },
    setZip (state, payload) {
      state.zip = payload
    }
  },
  actions: {}
}

export default Form

@/store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import Form from './modules/form'

Vue.use(Vuex)

const store = new Vuex.Store({
  modules: {
    formModule: Form,
  }
})

export default store

@/main.js

// your imports
import store from './store/index'
// your configurations
new Vue({
  el: '#app',
  router,
  store, // include store in your main Vue instance for accessibility with this.$store
  axios,
  components: { App },
  template: '<App/>'
});

Your SelectState.vue component would look like this:

<template>
  <div id="select-state">
    <span>{{ label }}</span>
    <select v-model="selectedState">
      <option v-for="state in states" :key="state">
        {{ state }}
      </option>
    </select>
  </div>
</template>

<script>    
export default {
  name: 'select-state',
  data: function () {
    return {
      states: ['TX']
    }
  },
  computed: {
    selectedState: {
      get() { return this.$store.state.formModule.state },
      set(value) { this.$store.commit('formModule/setState', value) }
    }
  },
  props: ['label']
}
</script>

The SelectZip.vue component would be similar, but using the store's zip as the v-model instead.

Your store variables are accessible throughout your application and can be accessed using computed properties in your components.

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

Event Stencil Emitter Unclear

I am in the process of developing a web component using stencil and react. The issue I am facing is that even though the value is emitted, it appears as undefined when called within the component. @Event() newModuleClicked: EventEmitter<any>; ...

Is it possible to sketch basic 2D shapes onto 3D models?

Is the technique called projective texture mapping? Are there any existing library methods that can be used to project basic 2D shapes, such as lines, onto a texture? I found an example in threejs that seems similar to what I'm looking for. I attempt ...

What are the steps to access an Alexa skill through a web browser?

I recently developed an Alexa skill for recipe recommendations. I am wondering if it is possible to have the skill open a browser on my phone and display the recipe when I say, "Alexa, send me the recipe"? The skill is working perfectly in the Alexa devel ...

Utilizing Bootstrap CSS within Vue's scope

I'm attempting to integrate Bootstrap into a Vue component while ensuring that all CSS is scoped. My initial approach was as follows: <style scoped> @import "~bootstrap/dist/css/bootstrap.css"; @import "~bootstrap-vue/dist/bootstrap-vue.css"; & ...

Utilize communication channels to access electron's main process functions from the render process once deployment is complete

Hey there, I'm facing a challenge with accessing methods from my index.js main process in the render process. I've experimented with two different approaches to solve this issue. ipcMain and ipcRender Initially, I attempted to utilize ipcMain an ...

Guide to generating an array of slot indexes within Vue.js

In the process of developing my personalized carousel, I have chosen to incorporate images using the <img> tag. However, I find that utilizing the Vue method for creating a carousel component offers more flexibility, especially since I intend to inte ...

Tips for dynamically importing a component

I am currently working on developing a versatile form field in Vue that can be customized to utilize different widgets for input. My goal is to create a collection of inputs, import the necessary one, and incorporate it into my component. However, I am fac ...

I am having trouble getting the jsTree ajax demo to load

I am having trouble running the basic demo "ajax demo" below, as the file does not load and the loading icon continues to churn. // ajax demo $('#ajax').jstree({ 'core' : { 'data' : { ...

What steps should be taken for the authentication process when using Active Directory (with LDAP) with an AngularJS/JavaScript frontend?

Currently, I am tackling a project that involves authenticating users in an application using their Windows credentials. The frontend is built with AngularJS and the backend with Java. After conducting extensive research, I came to the realization that it ...

The entrance animation kicks off while the exit animation is still in progress

I am looking to implement a slide and fade transition in my Vue routing. The effect I am trying to achieve can be seen here: https://discord.js.org/#/docs/main/stable/general/welcome In this desired effect, the "old" page slides to the right and fades out ...

What techniques are most effective for creating unit tests in a Node.js environment?

One of the challenges I am facing is writing a unit test for a module where I load a mustache template file. To tackle this, I am exploring the use of mocha, chai, and rewire. Below is an excerpt from my module.js: var winston = require('winston&apo ...

I'm attempting to render HTML emails in ReactJS

I have been attempting to display an HTML page in React JS, but I am not achieving the same appearance. Here is the code snippet I used in React JS: <div dangerouslySetInnerHTML={{ __html: data }}/> When executed in regular HTML, the page looks lik ...

Ways to incorporate the CSS class name within the MUI createTheme palette color reference instead of using a hardcoded name

How can I dynamically insert a CSS class name inside the Material-UI(MUI) createTheme palette color instead of hardcoding it? const theme = createTheme({ palette: { primary: { light: "#66b53f", main: * ...

Snatching the lesson found within an iframe

Is it possible to obtain the id from an iframe using the following method? var iFrame = window.top.document.getElementById('window_<?php echo $_product->getId() ?>_content'); However, I am struggling to understand how to retrieve the c ...

Adjust image loading according to screen dimensions

I am working on HTML code that currently displays an image. The code looks like this: <div> <img id="wm01" alt="PP" title="PP" u="image" src="theImages/wm01.jpg" /> </div> My goal is to show a different image based on the screen si ...

Using PHP and JavaScript to determine device screen width and eliminate the $_GET parameters from the URL

I have implemented the following JavaScript code to detect screen width and utilize it as a constant throughout my template files using conditional statements to control the visibility of different sections on my site. Just to clarify, I am working within ...

Using Node.js to parse JSON data fetched from the web

My current challenge involves retrieving and parsing JSON from a web API (https://api.coinmarketcap.com/v1/ticker/?limit=3) in order to extract the name and price_usd fields. For example: [ { ... sample data provided ... } ] The code snippet I am wo ...

What is the best way to create a nested match using regex?

const foundMatches = regExPattern.match(/\((.+?)\)/g); When tested against: [example[1]] The result is "[example[1]", indicating a potential nesting issue. How can this be resolved? ...

Ways to integrate npm dependencies into your Cordova plugin

Currently working on implementing a Cordova plugin called core-cordova found in this repository. This particular plugin has a dependency on another NPM package. The issue arises after installing the plugin in my app using: $ cordova plugin add @aerogears ...

An error occurs when trying to call a function that is defined within the methods{} block from outside

export default{ name: 'navigation', components:{ menuIcon, }, data() { return { mobile: null, mobileNav: null, windowwidth: null, } }, methods: { checkScreen() { this.windowwidth = window.innerWidth ...