vue 对获得数据进行筛选,通过computed做筛选,得到的值第一次为空,第二次才有值

html

 <div class="content_img clear">
      <a  :href="img.src" class="block"  v-bind:style="{backgroundImage: 'url(' + img.url + ')'}"  v-for="(img,index) in filteredStyle">
          <div class="tx">{{img.name}}</div>
          <div class="xq">
               <div>
                     <span class="fl">{{img.type}}</span>
                     <span class="fl n">1张</span>
               </div>
          </div>
          <span class="sc" v-on:click="sC(img.url,img.type,index)" :class="{'a':classItem.indexOf(img.url)>=0}" v-on:click.prevent=""></span>
     </a>
 </div>

js

data: {
     img: { url:"",name:"",type:""}, imgS:[]
}
 mounted: function(){
             Vue.http.get('js/common1.json').then((response) => {
                console.log(1)
              vm.$data.imgS=response.data;
             })
          },
 computed: {
          filteredStyle: function () {
               console.log(2);
               var self = this;
               console(this.imgS[0]);
               return this.imgS[0];
         }
        }

运行结果是
2//先运行computed
1//运行mounted
2//数据变化再次执行computed
imgS[0]的值//能够打印出值,但是不能提供给html里面,所以页面没有变化

问题:怎么样才能得到computed第二次执行的数据呢?是不是它只传递第一次的值呢?

阅读 5.3k
2 个回答

直接賦值就好了,不需要經過computed

  data(){
       return {
                filteredStyle:{}
        }
     },
       
    mounted(){
    
                 this.$http.get('js/common1.json').then((response) => {
                      this.imgS=response.data;
                      this.filteredStyle =this.imgS[0]
             })
    
    }

建议去了解下 vue 的生命期,一些钩子函数等。

我猜想你应该是因为页面样式中绑定了这个 filteredStyle,而在它第二次计算前,页面显示不如自己预期才问这个问题的吧?其实可以用个 v-if 或者 v-else 指令,让这部分内容当这变量是正常值的时候再显示嘛……

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