Vue渲染初始化

1.在做一个答题的界面,选择答案后会根据对错来变色,如下图,但是在点击进入下一题时,样式不会重置,没有选题情况下,不是默认的黑色
图片描述

2.对应的html代码

<div class="H-flex-item" id="ti">
    <!--题目-->
    <div class="H-text-list H-flexbox-horizontal  H-theme-background-color-white H-border-vertical-bottom-after H-vertical-middle H-touch-active">
        <div class="H-flex-item H-padding-horizontal-both-10 H-font-size-16 H-padding-vertical-both-12 H-text-show-row-5" style="line-height: 29px;">
           {{lists.title}} 
        </div>
    </div>
    <!--选项-->
    <div class="H-padding-vertical-bottom-5"></div>
    <div  v-for="(list,index) of lists.options" @click="ans(index,lists)" ref="items" class=" H-text-list H-flexbox-horizontal  H-theme-background-color-white H-border-vertical-bottom-after H-vertical-middle H-touch-active">
        <div class=" H-flex-item H-padding-horizontal-both-10 H-font-size-16 H-padding-vertical-both-12 H-text-show-row-3" style="line-height: 29px;">
                {{list}}
        </div>
    </div>
</div>

3.对应的js代码

//实力化vue
var vm = new Vue({
    el:"#ti",
    data:{
        lists:'',
        items:''
    },methods:{
        ans:function(index,lists){
            var answer = ['A','B','C','D'];
            if(lists.an==answer[index]){
                H.toast('答对了');
                this.$refs.items[index].style.color = 'limegreen'; 
            }else{
                this.$refs.items[index].style.color = 'red'; 
            }
        }
    }
});
阅读 2.3k
2 个回答

不需要用refs获取dom,给答对了和打错了设置不同的类,在渲染的时候判断是答对还是打错,来设置不同的类,也可以直接在html里设置style

<div  v-for="(list,index) of lists.options" @click="ans(index,lists)" ref="items" class=" H-text-list H-flexbox-horizontal  H-theme-background-color-white H-border-vertical-bottom-after H-vertical-middle H-touch-active" :style="color: ['A','B','C','D'].indexOf(list.an) > -1 ? 'limegreen' : 'red'">
        <div class=" H-flex-item H-padding-horizontal-both-10 H-font-size-16 H-padding-vertical-both-12 H-text-show-row-3" style="line-height: 29px;">
                {{list}}
        </div>
    </div>

可以判断当前问题答案那个值是否为空,没有那个样式就是初始化的,有的话就是答案就是红色的就行了吧

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题