每个单独元素的Vue js切换类 [英] Vue js toggle class of each individual element

查看:32
本文介绍了每个单独元素的Vue js切换类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然在 Vuejs 中有很多切换类的例子,但我还没有找到一个切换类来缩小元素范围的例子.如果我像这样定义一个全局变量:

While there are many examples of toggling classes in Vuejs, I am yet to find one that toggles a class narrowing down the scope of the element. If I define a global variable like this:

data: {
  toggle: false
}

当我有一个元素时会遇到问题,比如这个导航栏:

I will run into a problem when I have an element, like this navigation bar:

<ul class="menu">
  <li class="has-dropdown" v-bind:class="{ 'is-open': toggle }" @click="toggle = !toggle">
    Foo
    <ul class="dropdown">
      <li>Dropdown Item 1</li>
      <li>Dropdown Item 2</li>
    </ul>
  </li>
  <li class="has-dropdown" v-bind:class="{ 'is-open': toggle }" @click="toggle = !toggle">
    Bar
    <ul class="dropdown">
      <li>Dropdown Item 1</li>
      <li>Dropdown Item 2</li>
    </ul>
  </li>
</ul>

看看这里发生了什么?如果我单击这两个元素之一,两者都会同时切换类,因为它正在更改全局变量.现在,我将如何切换 only 被点击元素的类?

See what happens here? If I click in one of these two elements, both are going to toggle the class at the same time, because it's changing a global variable. Now, how would I toggle the class of only the element that is clicked?

推荐答案

VueJS(以及大多数其他现代 Web 框架)的基本指导原则是一切都来自模型.

The fundamental guiding principle of VueJS (and most other modern web frameworks) is that everything comes from the model.

你从不谈论操纵 DOM;相反,您可以创建一个模型来描述您想要的效果.

You never talk about manipulating the DOM; instead, you make a model that describes the effect you want.

就您而言,这意味着您需要两个 data 属性,而不是一个.

In your case, that means you want two data properties, not one.

然而,您实际上应该做的是使每个列表项成为自己的子组件(然后将获得自己的模型).使用slots在每个slots中指定不同的内容.

However, what you should actually do is make each list item its own child component (which will then get its own model). Use slots to specify different content in each one.

这篇关于每个单独元素的Vue js切换类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆