【问题标题】:Toggle show/hide on specific element with Vue.js (cdn)使用 Vue.js (cdn) 在特定元素上切换显示/隐藏
【发布时间】:2019-05-25 15:10:45
【问题描述】:

我正在使用 Vue.js (cdn) 和 axios 从 heroku 和 mlab 获取内容。

我想显示列表中对象的一些信息,并且我希望每一行都像一个 按钮或具有某种 onclick 以显示来自下面同一对象的更多信息。就像一个下拉菜单。

我尝试了按钮 v-on:click="visible = !visible"... 这很有效,但它会按预期切换所有元素的显示/隐藏。

我希望能够在多个列表中的单个元素上切换显示/隐藏。

这就是我所拥有的:

index.html

<div id="app">
    <div class="list" v-for="drinks in rom">
        <button v-on:click="visible = !visible">{{ drinks.brand }}</button>

        <div class="hidden" v-show="!visible">
            <p> {{ drinks.comment }} </p>
        </div> 
    </div><!--list-->
    </div><!--app-->

ma​​in.js

new Vue({
el: '#app',
data() {
    return {
        rom: null,
        visible: true
    }
},
mounted() {
    axios
        .get('******')
        .then(response => (this.rom  = response.data))
}})

我能做什么?

【问题讨论】:

    标签: javascript html vue.js


    【解决方案1】:

    你可以给你的饮料对象添加一个可见的属性,然后

    v-on:click="drink.visible = !drink.visible"
    

    或者您可以创建一个与您的饮料映射的数组,其中 id 作为键,true 或 false 作为值,然后:

    v-on:click="drinksVisibility[drink.id].visible = !drinksVisibility[drink.id].visible"
    

    【讨论】:

      【解决方案2】:

      你可以在每个对象中拥有一个可见的属性并渲染元素

      rom : [{brand: 'drink1',visible: false,comment: 'drink1 - comment'},
        {brand: 'drink2',visible: false,comment: 'drink2 - comment'}]
      

      然后编写一个切换函数来显示/隐藏元素,通过传递一个索引值来修改特定对象的可见值真/假

      &lt;button v-on:click=toggle(index)&gt;{{ drinks.brand }}&lt;/button&gt;

      示例:https://codepen.io/sandeep821/pen/YdxjWg

      【讨论】:

        【解决方案3】:

        您需要将 rom 声明为数组:

        data() {
            return {
                rom: []
            }
        },
        

        然后,您可以为 API 响应中的每个数据项添加 visible 属性:

        mounted() {
            axios
                .get('******')
                .then(response => (this.rom = response.data.map(drinks => {
                        drinks.visible = true;
                        return drinks;
                    })
                ))
        }})
        

        然后,您可以在 v-for 的每个循环中使用该 visible 属性:

        <div class="list" v-for="drinks in rom">
            <button v-on:click="drinks.visible = !drinks.visible">{{ drinks.brand }}</button>
        
            <div class="hidden" v-show="!drinks.visible">
                <p> {{ drinks.comment }} </p>
            </div> 
        </div><!--list-->
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-10-02
          • 1970-01-01
          • 2017-08-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-12-20
          • 1970-01-01
          相关资源
          最近更新 更多