Динамическая модальность Использование индекса в качестве идентификатора VueJS - PullRequest
0 голосов
/ 10 сентября 2018

Надеюсь, что кто-то может помочь.

Я впервые использую Vue, и меня попросили создать страницу команд, которая извлекает данные из списка, группирует имена по имени команды в массив и отображает ихв формате карты.Мне удалось все это сделать, однако, когда щелкают карточки, я хочу, чтобы все члены команды и их роль (например, разработчик, менеджер продукта и т. Д.) Отображались в модальном виде вместе с изображением команды

Я использовал индекс в качестве идентификатора для каждой карты, которая работает нормально, но я не уверен относительно того, как передать его модалу для отображения правильных членов для каждой команды при нажатии на карту.Я пробовал различные методы, которые я нашел здесь, но ни один из них, похоже, не относится именно к тому, что я делаю, и мое отсутствие знаний Vue мешает мне, поскольку я могу легко сделать это с обычным HTML / JS.

Также, вероятно, стоит упомянуть, что из-за рабочих разрешений ПК и того факта, что он построен на SharePoint, мне приходится использовать Vue CDN и реализовывать его в 1 HTML-файле вместо использования компонентов.

Заранее большое спасибои я надеюсь, что это имеет смысл

Вот мой HTML:

        <div class="container">
        <h1 class="page-heading">MEET<span style="color:#ff0000">IN</span>G THE TEAM</h1>
        <p class="intro-text">This is a chance for you to tell your Country and the other teams who you are and what you stand for. You’ll
            need a team name, team mascot image, who’s in your team and what you want to say to the world.</p>
        <br>
        <button class="btn btn-outline-light" type="button" role="button" data-target="#create-modal" data-toggle="modal" id="create-team">Create a New Team</button>
        <button class="btn btn-outline-light" type="button" role="button" data-target="#create-modal" data-toggle="modal" id="update-team">Update Your Team</button>

        <div class="row" id="team-cards">
            <div class="col-md-4" v-for="(team, index) in teams" :key="team[0].teamname" v-if="team[0].teamname !== 'No Team'">
                <a href="'#teamModal' + index" data-toggle="modal">
                <div class="card" v-bind:id="index">
                    <img v-bind:src="teammate.teamimage" class="card-img-top" v-for="teammate in team" v-if="teammate.teamimage !== null" :key="teammate.teamimage">
                    <div class="card-body">
                        <h5 class="card-title"><strong>{{ team[0].teamname }}</strong></h5>
                        <p class="card-text" v-for="teammate in team" v-if="teammate.teamdescription !== null" :key="teammate.teamdescription">{{ teammate.teamdescription }}</p>
                    </div>
                    <div class="card-footer">
                        <img class="group-image" v-for="teammate in team" v-if="teammate.hackertype !== 'Developer'" :key="teammate.hackertype" src="https://community.global.hsbc/sites/DigiHub/SiteAssets/hub_assetts/Hack%20Teams/Images/red%20group.png">
                        <!-- <img class="group-image" v-for="teammate in team" v-else-if="teammate.hackertype !== 'Product Manager' || teammate.hackertype == 'Developer'" :key="teammate.hackertype" src="https://community.global.hsbc/sites/DigiHub/SiteAssets/hub_assetts/Hack%20Teams/Images/yellow%20group.png"> -->
                        <!-- <img class="group-image" v-for="teammate in team" v-if="teammate.hackertype == 'Developer' || teammate.hackertype == 'Product Manager'" :key="teammate.hackertype" src="https://community.global.hsbc/sites/DigiHub/SiteAssets/hub_assetts/Hack%20Teams/Images/green%20group.png"> -->
                        <a href="https://community.global.hsbc/sites/DigiHub/SitePages/Hack-Chat.aspx" target="_blank">
                            <img class="chat-image" src="https://community.global.hsbc/sites/DigiHub/SiteAssets/hub_assetts/Hack%20Teams/Images/chat.png">
                        </a>
                    </div>
                </div>
                </a>
            </div>
        </div>
    </div>

    <!-- Team Modal -->
    <div class="modal fade" v-bind:id="['teamModal'+index]" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><b>{{ team[0].teamname }}</b></h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <br>
                <div class="modal-body" v-for="teammate in team">   
                    <p>{{ teammate.name }}</p>
                    <p>{{ teammate.hackertype }}</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

И мой VueJS:

$(function () {

var appTeamCards = new Vue({
    el: '#app-teams',
    data: {
        teams: [],
        teamMembers: [],
    },
    mounted: function() {
        this.getTeams();
    },
    methods: {
        getTeams: function() {
            var self = this;
            $.ajax({
                url: '/sites/DigiHub/_api/web/lists/getbytitle(\'global-hackathon-reg\')/items?$orderby=Modified desc',
                method: "GET",
                headers: {
                    "Accept": "application/json;odata=verbose"    
                },
                success: function (data) {
                    var posts = data.d.results;
                    readData(posts);
                    console.log(self.teams);
                },
            });

            function readData(data) {
                self.teams = groupBy(data, "teamname");  
            };

            function groupBy(collection, property) {
                var i = 0, val, index,
                    values = [], result = [];
                for (; i < collection.length; i++) {
                    val = collection[i][property];
                    index = values.indexOf(val);
                    if (index > -1)
                        result[index].push(collection[i]);
                    else {
                        values.push(val);
                        result.push([collection[i]]);
                    }
                }
                return result;
            }

        },

    }
}); 

$('#update-team').click(function(){
    $("#new-member-form").hide();
    $("#reg-another-update").show();
    $("#update-form").show();
});

$('#create-team').click(function(){
    $("#new-member-form").show();
    $("#update-form").show();
    $("#reg-another-update").hide();
});

$('#reg-another-update').click(function(){
    $("#new-member-form").show();
    $("#reg-another-update").hide();
    $("#update-form").hide();
});

$('#submit-team-btn').click(function(){
    $("#update-form").attr("disabled", "disabled");
});

});

1 Ответ

0 голосов
/ 11 сентября 2018

Кажется, у меня было правильное решение, но синтаксис был немного неправильным. Я внес следующие изменения, и теперь мой код работает, как и ожидалось.

Ссылка на привязку карты должна быть записана следующим образом:

<a :href="'#teamModal' + index" data-toggle="modal">

Модальный ID:

<div class="modal fade" :id="'teamModal' + index" v-for="(team, index) in teams" :key="team[0].teamname" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
...