VueJS: Connecting data to Components

I'm struggling to articulate this question clearly, and the documentation isn't providing the answers I need.

Essentially, in my dataset, I have an array with two values that represent the day of the week index. I want to create a custom range component with added functionalities. For instance, my range slider will have two handles, although I haven't styled them yet.

Vue.component('range', {
  props: [ 'step', 'min', 'max', 'value' ],
  created() {
    this.minValue = this.value[0];
    this.maxValue = this.value[1];
  },
  data: function() {
    return {
      minValue: 0,
      maxValue: 0
    }
  },
  template: `<div>
    <input type="range" name="points" :min="this.min" :max="this.max" :step="this.step" :value="minValue">
    <input type="range" name="points" :min="this.min" :max="this.max" :step="this.step" :value="maxValue">
  </div>`
});

window.app = new Vue({
  el: '#app',
  data: {
    'weekdays': [ 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' ],
    'locations': [
      {
        'id': 1,
        'name': 'Test Place',
        'hours': [
          {
            'id': 1,
            'weekdays': [ 0, 4 ]
          },
          {
            'id': 2,
            'weekdays': [ 5, 5 ]
          },
          {
            'id': 3,
            'weekdays': [ 6, 6 ]
          }
        ]
      }
    ]
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
  <div class="location" v-for="(location, index) in locations">
    <h3>{{ location.name }}: {{ location.id }}</h3>
    <div class="hours">
      <div v-for="(hour, index) in location.hours">
        <p>Hour ID: {{ hour.id }}</p>
        <range step="1" min="0" max="6" :value="hour.weekdays"></range>
      </div> 
    </div>
  </div>
</div>

The example above represents my current progress. My question now is whether there's a way to utilize v-model without having to emit the data back to the parent component. Is it possible to update the array based on the values from the sliders within the main component?

For example:

<range step="1" min="0" max="6" :value="hour.weekdays" v-modal="hour.weekdays"></range>

Answer №1

v-model is essentially a shortcut for

<some-component
    v-bind:value=""
    v-on:input="">
</some-component>

This means you can achieve the same functionality of `v-model` on a component by incorporating internal watchers in the component and triggering an event with an array value.

Vue.component('range', {
  props: [ 'step', 'min', 'max', 'value' ],
  created() {
    this.minValue = this.value[0];
    this.maxValue = this.value[1];
  },
  data: function() {
    return {
      minValue: 0,
      maxValue: 0
    };
  },
  methods: {
    emitOut() {
    this.$emit('input', [this.minValue, this.maxValue]);
    },
  },
  watch: {
    minValue(newVal) {
    this.emitOut();
    },
    maxValue(newVal) {
    this.emitOut();
    },
  },
  template: `<div>
    <input type="range" name="points" :min="this.min" :max="this.max" :step="this.step" v-model="minValue">
    <input type="range" name="points" :min="this.min" :max="this.max" :step="this.step" v-model="maxValue">
  </div>`
});

window.app = new Vue({
  el: '#app',
  data: {
    'weekdays': [ 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' ],
    'locations': [
      {
        'id': 1,
        'name': 'Test Place',
        'hours': [
          {
            'id': 1,
            'weekdays': [ 0, 4 ]
          },
          {
            'id': 2,
            'weekdays': [ 5, 5 ]
          },
          {
            'id': 3,
            'weekdays': [ 6, 6 ]
          }
        ]
      }
    ]
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
  <div class="location" v-for="(location, index) in locations">
    <h3>{{ location.name }}: {{ location.id }}</h3>
    <div class="hours">
      <div v-for="(hour, index) in location.hours">
        <p>Hour ID: {{ hour.id }}</p>
        First: {{ hour.weekdays[0] }}
        Second: {{ hour.weekdays[1] }}
        <range step="1" min="0" max="6" v-model="hour.weekdays"></range>
      </div> 
    </div>
  </div>
</div>

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

What is the best way to identify when a particular character has been entered into the input field?

HTML <div class="form-group"><label class="col-md-4 control-label" for="s1">URL</label> <div class="col-md-4"><input id="url" name="url" type="text" ng-change="checkVal()" ng-model="url" placeholder="" class="for ...

Switch the following line utilizing a regular expression

Currently, I am facing a challenge with a large file that needs translation for the WordPress LocoTranslate plugin. Specifically, I need to translate the content within the msgstr quotes based on the content in the msgid quotes. An example of this is: #: . ...

"Concealed beneath the text is the link to return to the

I have implemented a back to top link in my MVC project. Layout: <a id="back-to-top" href="#" class="btn btn-primary btn-lg back-to-top" role="button" title="Click to return to the top of the page" data-toggle="tooltip" data-placement="left"><spa ...

The correct conclusion is reached by the function when the console.log statement is placed above the function call

By moving the console.log above the function call, the correct conclusion is reached. I double-checked multiple times by toggling the console.log on and off. Running on node.js v16.4.2. The input data is accurate. I attempted to replicate the issue in a di ...

What is the best way to save information from an axios promise into my database on separate lines?

Having a technical issue and seeking assistance: Currently, I am encountering an issue with my axios request to the database. After successfully retrieving the data, I aim to display it in a select form. However, the response is coming back as one continu ...

Tips for preventing the creation of an element in AngularJS

When working with Angular, I encountered an issue with creating an <iframe> element only upon user interaction. Initially, I simply placed the element on the page and used the ng-if directive to bind its presence to a boolean in my model. However, I ...

I am encountering the ERR_STREAM_WRITE_AFTER_END error in my Node.js API. Does anyone know how to resolve this problem?

When I try to upload a file using the API from the UI, I encounter the following issue. I am interacting with a Node.js API from React.js and then making calls to a public API from the Node.js server. https://i.stack.imgur.com/2th8H.png Node version: 10. ...

Having trouble with the CSS positioning of divs created with JavaScript: it's not behaving as anticipated

Let me start by saying I have always struggled with CSS positioning. It seems like I am missing something simple here... So, I have a JS script that generates divs within a parent container called #container which is set to absolute position. Here is the ...

The CSS transition fails to function correctly when rendering a React element within an array

When rendering a React component within an array using CSS transitions, I noticed that the elements in the array re-order and change style. Surprisingly, only the elements moving up have transitions applied, while the ones moving down do not. I expect all ...

Extracting data from an HTML image in Django: A step-by-step guide

I am facing a challenge of adding links to multiple images generated in HTML from local folders. These links should be triggered by a view function called create_pc, which will also receive the image path as a parameter. Here is a snippet from my HTML fil ...

Using JQuery to rebind() after resetting the count

In my game, I have implemented a feature to ensure that the start button can only be clicked once each time it appears in order to prevent the function from loading multiple times. I wrote some code that tracks the number of clicks and unbinds the click e ...

jQuery Ajax Pagination - The first page and the selected one function correctly, but the rest do not

Allow me to provide a more detailed description of my issue than what is indicated in the title... I am utilizing CodeIgniter pagination (adjusted to accommodate Bootstrap's requirements), and have set it up to display my links as follows: <div cl ...

Unpacking arguments in Typescript functions

I have a function to update todo items in the database, like this: async function update({id, ...todoInfo }: ITodo) { const db = await makeDb() const foundTodo = await db.collection('todos').updateOne({ _id: transformId(id) }, { $set: { . ...

Ways to access button text using the vue-test-utils

Is there a way to extract the text from a button element that is found using vue-test-utils? I am currently using v1.0.0-beta.10 Here is an example button element in my vue file: el-button(@click.native="cancel", size="small", native- ...

Are there any nodeJS template engines similar to C#'s RazorEngine?

Is there a template engine for Node.js that is similar to RazorEngine, specialized in generating HTML but also capable of handling other types of output? I am looking for a tool that can dynamically create JavaScript files along with HTML content like Razo ...

Removing a value from a JSON object by utilizing the .map function

My JSON object is structured as follows: [{"box":1,"parent":[],"child":[{"boxId":2},{"boxId":3}]},{"box":2,"parent":[{"boxId":1}],"child":[]}] I am attempting to remove the element "child":[{"boxId":2} with boxId=2 from the object. I have tried using a , ...

Preventing Deselection of v-list-item in Vuetify3: A Quick Guide

I am struggling with maintaining the highlight of a selected item in a list of names. Currently, clicking on an item highlights it in blue, but clicking on it again removes the highlight while keeping the selectedUser value the same. How can I prevent the ...

Having trouble displaying a local JSON file in React?

I've been troubleshooting this issue with a local JSON file. The console.log shows that all values are being returned correctly, confirming that the path is accurate. However, when attempting to extract the 'name' input value, I encounter th ...

Ways to manage numerous AJAX actions within a single HTTP request?

Currently, I am utilizing jQuery to create a multipart web page containing a list of links that are updated through periodic AJAX HTTP requests. Each link on the page is triggered by a timer in JavaScript, causing it to make an HTTP request to its designat ...

Tips for implementing a JavaScript Material Design framework in ReScript code?

I am attempting to integrate the material-ui library into a Rescript/React application. The code snippet below demonstrates how to display a button: @module("@material-ui/core/Button") external button: string = "default" @react.compone ...