我只是想知道怎么做.js方式,现在我可以在单个项目上切换active类,当我单击其他项目时,active类仍然出现在前一个项目上,以下是我的设置:

FileOne.vue (Parent component)

// Say that I have 5 Items I am rendering here:
<template>
  <ul v-for="item in items">
    <my-list-item :item-title="article.title"
                  :item-content="article.content"> </my-list-item>
  </ul>
</template>

<script>
  import Items from './FileTwo'
  export default {}
</script>

fileTwo.vue (Child components)

// When I click each Item the `active` class should be applied to the current Item and removed from previous item:
<template>
  <li :class="{'active': isRowActive}" @click.stop="toggleRowActive">
    <h1>{{articleTitle}}</h1>
    <p>{{itemContent}}</p>
  </li>
</template>

<script>  
  export default {
    name: 'my-list-item',
    data: function () {
      return {
        isRowActive: false,
      }
    },
    props: {
      articleTitle: String,
      articleContent: String,
    },
    toggleRowFn() {
      this.isRowActive = !this.isRowActive;
      this.showBtnReadContent = true;
    },
  }
</script>

推荐答案

可能的解决方案之一:https://jsfiddle.net/wostex/63t082p2/28/

其主要思想是:如果要处理父状态之外的子状态,应该从子状态发出"change property"事件,并在父状态内处理计算.在我的示例中,我将活动Li索引存储在父数据中,如果当前索引是否活动,则发送子布尔属性active.

<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app">
<ul>
  <my-list-item :title="item.title"
      :content="item.content"
      v-for="(item, index) in items"
      :active="index === activeLiIndex"
      :index="index" 
      :key="item.title"
      @newactive="activeLiIndex = $event"      
      ></my-list-item>
</ul>
</div>

<script type="text/x-template" id="my-list-item">
  <li :class="{'active': active}" @click.stop="toggleRowActive">
    <h1>{{title}}</h1>
    <p>{{content}}</p>
  </li>
</script>

new Vue({
    el: '#app',
    data: {
      items: [
        {title: 'Title 1', content: 'Content 1'},
        {title: 'Title 2', content: 'Content 2'}
      ],
      activeLiIndex: null
  },
  components: {
    'my-list-item': {
        template: '#my-list-item',
        props: ['title', 'content', 'active', 'index'],
        methods: {
          toggleRowActive() {
            this.$emit('newactive', this.index);
          }
        }
      }
    }
});  

此外,正如您所见,在您的 case 中,v-for用于子组件本身.在您自己的示例中,您生成了ul个标记,而不是常规的li个项目.

Vue.js相关问答推荐

如何根据数据库中的条件在vue中创建类

Vue 3 需要 main.js 中的文件

VueI18n 无法读取或更改组合 API 中的区域设置

有没有办法将react 键作为值传递给由 v-for 创建的 v-model

两个div元素之间的vue2过渡

在Vue cli项目中,Laravel api app放在哪里以及如何在vue js中调用api?

Vuejs 和 Laravel 发布请求 CORS

Vue.js 如何计算总数?

如何在 vuejs 中异步加载图像 src url?

在 v-for 的情况下如何从 v-model 输入更新 Vuex 存储

Nuxt & Vuetify:如何控制 CSS 文件的加载顺序?

事件 click点击的无效处理程序:未定义

Vue.js 无法切换字体真棒图标

如何克隆props对象并使其无react

如何在 vue.config.js 中为生产设置 API 路径?

如何异步验证 Vuetify 文本字段?

简单的点击功能不触发

VueJS 路由 - 使用子路由和 Vuetify 时如何停止多个活动路由(active routes)?

检测 Vue-Router 导航Guards中的后退按钮

如何在 vue3 中的setup方法中发出事件?