How can I improve my code so that I can generate unique instances of a Vue component with specific data attached to each one?

My Objective:

  • I need to utilize multiple select elements
  • Every time an option is selected, it should be added to a keyword array
  • Each keyword should then be displayed in a "tag" component
  • These tags should be removable, resulting in the removal of the associated keywords

Note: This is linked with Laravel and Blade templates, hence the @ before the mustache syntax.

Template

<select @change="switchType">
    <option v-for="type in types" value="@{{ type.value }}">@{{ type.text }}</option> 
</select>

...

<tag v-for="keyword in keywords" model="@{{ keyword.model }}" identifier="@{{ keyword.id }}" text="@{{ keyword.text }}"></tag>

JS

const API_TYPES = '/api/types';

var vm = new Vue({
    el: '.search',
    data: {
        types: [],
        type: null,
        keywords: [],
    },

    ready: function() {
        this.$http.get(API_TYPES).then(function(types) {
            this.$set('types', types.body)
        });
    },

    methods: {
        search: function() {
            if (this.type) {
                this.keywords.push({
                    model: 'type',
                    identifier: this.type.id,
                    text: this.type.name
                })
            }
        },

        switchType: function(event) {
            var self = this
            var value = event.target.value
            console.log(value)
            this.$set('type', {id: value, name: event.target[value].text})
            self.search()
        },
    },

    components: {
        'tag': {
            template: `
                <span class="tag is-warning is-medium">
                    {{ model }} {{ identifier }} {{ text }}
                    <button class="delete is-small" @click="removeTag"></button>
                </span>
            `,
            props: [
                'model',
                'identifier',
                'text'
            ],
            methods: {
                removeTag: function () {
                    this.$el.remove()
                }
            }
        }
    }
})

In summary: I am aiming to achieve something similar to this, but encountering issues with sending data for the yellow pill item despite successful creation.

Where could I be going wrong? As I am relatively new to this data-driven approach, any inconsistencies in my code would be greatly appreciated. Thank you!

Answer №1

You appear to be using Vue 2, but some of your syntax is from Vue 1. Here are a few adjustments you need to make:

The ready() lifecycle hook is no longer used; instead, use created():

created: function() {
    this.$http.get(API_TYPES).then(function(types) {
        this.$set('types', types.body)
    });
}

It's important to note that the use of handlebars for interpolation inside attributes has been removed in Vue 2. You should now use v-bind for binding data to attributes. For example, change @{{ type.text }} to v-bind:value="type.value":

<select @change="switchType">
    <option v-for="type in types" v-bind:value="type.value">@{{ type.text }}</option> 
</select>

Consider using v-model to bind select boxes easily. Here's an example markup and view model:

<select v-model="selected[0]">
    <option v-for="type in types" v-bind:value="type.value" v-text="type.text"></option>
  </select>

    <select v-model="selected[1]">
    <option v-for="type in types" v-bind:value="type.value" v-text="type.text"></option>
  </select>

var vm = new Vue({
  el: '#app',
  data: {
    types: [{
      value: 'foo',
      text: 'foo'
    }, {
      value: 'bar',
      text: 'bar'
    }, {
      value: 'baz',
      text: 'baz'
    }],
    selected: []
  }
})

If you want to perform actions when the selection changes, add a watcher as follows:

watch: {
    selected: function(val){
      // do something
      console.log('selected updated to: ' + val);
    }
}

For further guidance on migrating to Vue 2, refer to the official migration guide at https://v2.vuejs.org/v2/guide/migration.html. Visit https://v2.vuejs.org/v2/guide/ for Vue 2.0 documentation.

If you encounter any issues, check the console in your browser's developer tools for helpful error messages from Vue.

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

Dynamically refresh text content from a dropdown menu using AJAX

Seeking help in updating text from a select input using AJAX. The goal is to have the selected item appear or be updated in a <span>. This is my current setup: <?php echo '<select name="test">'; for ($i=0; $i <= 20; ...

Show the subscription response data in Angular

When utilizing the code snippets below from two different components, I am able to receive a valid response value from the subscriber. dataService.ts fetchFormData(){ return this.http.get('http://localhost:48116/RecuruitmentService.asmx/addRoleTest ...

Utilizing Vue.js to dynamically load JavaScript files depending on the environment

I have a JavaScript file that is generated by AWS Cognito, and its content varies depending on the environment. As I am not supposed to manually modify it, using Vue's environment variables may not be a feasible solution for me. How can I dynamical ...

The export of 'alpha' is not available in the '@mui/system' module

Help! I am encountering an error related to the @mui/material library. I have already looked into the package.json file of mui/system and it seems that 'alpha' is exported in it. ./node_modules/@mui/material/styles/index.js Attempted import erro ...

Retrieving the request body in AWS Lambda

Within my AWS Lambda function running on NodeJs 8.0 and receiving requests from API Gateway, the code is structured as follows: const mysql = require('mysql'); exports.handler = (event, context, callback) => { console.log("event.body = " ...

Obtain the total number of items in the list based on the applied filters and dynamically

My application initially shows the total number of posts based on the server's response. However, users have the option to filter these posts, and I need to dynamically update the post count according to the filtered results. inputFilter:function() ...

Material design for Angular applications - Angular Material is

Recently, I decided to explore the world of Angular and its accompanying libraries - angular-material, angular-aria, and angular-animate. I'm eager to experiment with this new styling technique, but it seems like I've hit a roadblock right at the ...

Resources for Vue.js stylesheets

Vue.js is my latest discovery and I have been experimenting with the single file component architecture. A small issue I encountered was that all of my components' styles were being loaded on the page, even if they weren't currently active. Is t ...

Assigning isolate scope property to ngSelect element's directive for the purpose of pre-selecting an option has proven to result in

Upon loading my page, the form is populated with values fetched from an http service. At the top of the form sits a custom directive, specifically a select box: .directive('categorySelectBox', function(){ return { restrict: "A", repla ...

Angular JS struggling to load JSON data

As a beginner in the world of AngularJS and JSON, I decided to test my skills with the following example. However, I am encountering some difficulty loading data from a JSON file: <body> <h2>AngularJS Sample Application</h2> < ...

Generate a string that will be utilized to interpret a JSON response

I can't seem to extract a specific element from a json using a dedicated function. Can someone please assist me with this issue? Here is the fiddle that I have created for reference: http://jsfiddle.net/jonigiuro/N5TTM/2/ CODE: var data = { "res ...

Is a Buefy carousel with vertical thumbnails what you're looking for

How can I change the orientation of thumbnails in the b-carousel tag from horizontal to vertical? This is my current code: <template> <b-carousel :indicator-inside="false"> <b-carousel-item v-for="(item, i) in 6" :key="i"> ...

Having trouble grasping the error message "Uncaught Typerror Cannot Read Property of 0 Undefinded"?

As I embark on creating my very first ReactJS website with Node in the back-end, I encountered an issue in fetching and printing data. While I successfully displayed the names, pictures, and emails of project members from the server, I faced an error when ...

The process of extracting information from a JSON object and converting it into a dictionary in Python

By using the JavaScript code below, I am sending data from JavaScript to views.py: Javascript: $(document).ready(function(){ console.log("js2 working"); var jsonData={},a=0,key; $("#submit-button").click(function(e){ e.preventDefault(); $(&apos ...

When making a jQuery ajax request to the Google Maps API, an error is returned stating "SyntaxError:

I'm trying to make an ajax call using jsonp to the Google Maps API v3, but it keeps ending up in the error function. In the Firefox console log, I see the following error message: SyntaxError: invalid label "results" : [ When I click on it, I can se ...

Leveraging global variables within Vuex state management strategy

I have successfully added custom global variables into Vue by injecting them. Here is the code snippet: export default function (props, inject) { inject('models', { register(name) { const model = require(`@/models/${name}. ...

What is the best way to ensure that the parent element is the same size as the child element?

Within a div element, there is an iframe: <div id="toolbarArea" class="toolbarArea" data-Date="11/2016"> <img id="toolbarTitle" width="15px" height="15px" src="../stdicons/derem/threePoints.png"> <iframe id="frTool ...

Finding the title of a checkbox within a specific row

I am facing an issue where I have a checkbox inside a grid, and I need to determine the header name of that specific element upon clicking a button located outside the grid. The structure of my grid is as follows: <thead class="k-grid-header"> &l ...

Tips for refreshing an element after modifying a data-* attribute

I have an element that has the following CSS style: #element:after { content: attr(data-percent); } In an attempt to change the data-percent attribute using jQuery, I used this code: $('#element').data('percent', '50%'); ...

"Exploring the intersection of Jest and GraphQL through integration testing with error

Currently, I am working on integration tests for my db and graphql server using jest as my test runner and assertions library. During each test, I verify that there are no errors by checking: const result = await graphql(schema, query); expect(result.err ...