简体   繁体   English

使用方法设置 v-bind:class 不起作用

[英]Setting v-bind:class with method not working

I am trying to set the style of a div with我正在尝试设置 div 的样式

    <div v-for="q in questions" v-bind:class="{seen:isseen(q),unseen:isunseen(q)}">

The problem is that these functions get computed for each q, but I also need them to get recomputed when a different variable updates.问题是这些函数是为每个 q 计算的,但是当不同的变量更新时,我需要重新计算它们。

     methods:{
       isseen: function(id_1){
         if(ans[id_1]==2)
           return true;
         else
           return false
       },
       isunseen:function(id_1){
         if(ans[id_1]!=2)
           return true;
         else
           return false;
       }
     }

Here, I need the在这里,我需要

    v-bind:class="{seen:isseen(q),unseen:isunseen(q)}"

computed even when ans[id_1] changes.即使ans[id_1]发生变化,也会计算。

I have looked at the computed and watch approach, but cannot figure out what will work here.我已经查看了computedwatch方法,但无法弄清楚这里的工作原理。

You can use filtered questions like this:您可以使用这样的过滤questions

<div v-for="q in filteredQuestions" :class="{seen:q.isseen,unseen:q.isunseen}">

computed: {
    filteredQuestions(){
        for(var i=0, ii=this.questions.length; i<ii; i++) {
            //this.questions[i].isseen = ...
            //this.questions[i].isunseen = ...
        }
    }
},

or computed function:或计算函数:

<div v-for="q in questions" v-bind:class="{seen:isseen(q),unseen:isunseen(q)}">

methods:{
    isseen: () => (id_1) => {
        //...
    },
    isunseen: () => (id_1) => {
        //...
    }
}

I figured out how to work with this.我想出了如何使用它。
In place of v-bind:class="{seen:isseen(q),unseen:isunseen(q)}" and subsequently checking ans[id_1]!=2 and ans[id_1]==2 , I instead did v-bind:class="{seen:ans[q]==2,unseen:ans[q]!=2} .代替v-bind:class="{seen:isseen(q),unseen:isunseen(q)}"并随后检查ans[id_1]!=2ans[id_1]==2 ,我改为v-bind:class="{seen:ans[q]==2,unseen:ans[q]!=2}

However, Vue cannot detect changes that look like ans[indexOfItem] = newValue [This means the v-bind:class will not be triggered by changes in ans ], so values must instead be set by Vue.set(ans, indexOfItem, newValue) for their effects to be reflected in reactive classes etc.但是,Vue无法检测到类似于ans[indexOfItem] = newValue [这意味着 v-bind:class 不会被ans的更改触发] 的更改,因此必须由Vue.set(ans, indexOfItem, newValue)设置值Vue.set(ans, indexOfItem, newValue)以使其效果反映在反应类等中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM