【问题标题】:Vue show modal click using data from JSONVue使用来自JSON的数据显示模态点击
【发布时间】:2019-11-23 13:38:01
【问题描述】:

我有 JSON

"8":{
    "name": "Dog",
    "age": 2,
    "showModal": false
},
"9":{
    "name": "Cat",
    "age": 7,
    "showModal": false
},

接下来我使用 v-for 来显示数据:

<div v-for="(animal, index) in animals" :key="index">
    <div>{{ animal.name }}</div> // Dog
    <div>{{ animal.showModal }}</div> // false
    <div @click="showModal(animal.showModal)">Show modal</div>

    <div v-show="animal.showModal">modal...</div>
</div>

方法函数:

showModal(showModal){
    showModal = !showModal;
}

但函数showModal 不会将值从false 更改为true。如何更改此值以显示模式?

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    如果你是从文件加载,你可以这样尝试:

    <div v-for="(animal, index) in animals" :key="index">
        <div>{{ animal.name }}</div> // Dog
        <div>{{ animal.showModal }}</div> // false
        <div @click="showModal(index)">Show modal</div>
    
        <div v-if="isItemClicked(index)">modal...</div>
    </div>
    

    在你的数据中初始化indexes: [],然后去看看你的索引是否在那个数组中。

    methods: {
        showModal(index) {
            this.indexes.push(index);
        },
        isItemClicked(index) {
            let test = false;
            this.indexes.forEach(i => {
                if (i === index) {
                   test = true;
                   break;
                }
            })
            return test;
        }
    }
    

    如果您需要更改 json 中的数据,则需要其他程序。

    我认为这很有帮助。祝你好运。

    【讨论】:

    • 没有帮助,仍然没有将值从 false 更改为 true
    • 你确定你传递truefalse 像布尔而不是字符串?等待您的animals 数据中有索引?你的名字出现了吗?
    • 你是从 json 文件加载数据吗?
    • @mere96 是的,我看到了动物的name,我在第二个&lt;div&gt; 中看到了false。类型 animal.showModal 是布尔值。
    • 现在检查答案。您可以在新数组中传递索引,然后检查索引是否在该数组中。我认为这是一个好主意。
    【解决方案2】:

    @clikc 中有错字。应该是@click

    【讨论】:

    • 是的,我改变了这个,但这不是问题
    【解决方案3】:

    模板:

    &lt;div @click="showModal(animal)"&gt;Show modal&lt;/div&gt;.

    方法:

    showModal(animal) {
        animal.showModal = true;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-28
      • 2020-02-09
      • 2021-12-30
      • 2021-03-16
      • 2016-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多