通过单击诸如v-model之类的列表项进行绑定

时间:2019-06-04 16:31:48

标签: vue.js

当前,我有一个下拉组件来选择本地化语言。

<template>
    <div class="localeDropdown">
        <dropdown
            v-model="selectedLocale"
            :items="locales"
            :toggle-label="localeLabels.language"
        />
    </div>
</template>

<script>
import { mapState } from '../scripts/store/appConfig';
import { appendQueryString } from '../components/queryUtils.js';

export default {
    data() {
        return {
            selectedLocale: '',
        };
    },
    computed: {
        ...mapState({
            locales: state => state.locales,
            localeLabels: state => state.localeLabels,
        }),
    },
    watch: {
        selectedLocale(locale) {
            const updatedQueryString = appendQueryString({ locale });

            window.location.search = updatedQueryString;
        },
    },
};
</script>

语言环境:

[
  {"value":"en","label":"English"},
  {"value":"es_mx","label":"Español"},
  {"value":"fr_ca","label":"Français"}
]

我正在尝试将下拉菜单更改为导航菜单中的移动设备列表。

这是我的导航移动组件中的列表:

<ul class="navMobile__list">
    <li
        v-for="(subNavItem, index) in navItem.children"
        :key="index"
        class="navMobile__list__item"
    >
        <a
            :href="subNavItem.url"
            class="navMobile__list__item-link"
        >            
            <span class="navMobile__list__item-label">{{ subNavItem.label }}</span>
            <span
                v-if="subNavItem.isEnabled"
                class="navMobile__list__item-icon-enabled"
            >
                <span class="icon icon--tick">
                    <svg class="icon-inner">
                        <title>Enable</title>
                        <use xlink:href="#tick" />
                    </svg>
                </span>
            </span>
        </a>
    </li>
</ul>

enter image description here enter image description here

当前,下拉列表通过v-model更新所选语言。是否可以通过单击列表项来获得类似的功能?

1 个答案:

答案 0 :(得分:1)

我建议使用<button>代替<a>,因为这些选项实际上并不代表链接。无论如何,添加一个@click处理程序就足够了

<li
    v-for="(subNavItem, index) in navItem.children"
    :key="index"
    class="navMobile__list__item"
>
    <button
        class="navMobile__list__item-button"
        @click="selectLanguage(subNavItem.value)"
    >            
        <span class="navMobile__list__item-label">{{ subNavItem.label }}</span>
        <span
            v-if="subNavItem.isEnabled"
            class="navMobile__list__item-icon-enabled"
        >
            <span class="icon icon--tick">
                <svg class="icon-inner">
                    <title>Enable</title>
                    <use xlink:href="#tick" />
                </svg>
            </span>
        </span>
    </button>
</li>

在您的方法中定义点击处理程序:

methods: {
    selectLanguage(value) {
        // Change language to indicated value
    }
}