【问题标题】:Vue.js - Pass prop into $.each() (in mounted)Vue.js - 将 prop 传递到 $.each() (已安装)
【发布时间】:2021-02-20 03:57:42
【问题描述】:

当我的组件被挂载时,我需要遍历一个对象字面量。但是我很难在.each() 函数中使用道具数据。在each() 函数内,当我检查console.log 时,道具数据是“未定义的”。我的代码如下所示:

    [..]
      props: {
       active_categories: String,  // example: "0,1,2,4", might also be NULL
       category_list: Array  // example: [ 0:{ID:0, Status:0}, 1:{ID:1, Status:0} [..] ]
      },
    
      mounted: function(){

        // iterate through the prop array 'category_list'
        // if an ID of this array is included in the string 'active_categories', 
        // set 'Status=1'
          
        $.each(this.category_list, function(key, value, active_categories) {
    
            if(active_categories){
    
              if(active_categories.includes(value.ID)){
                   value.Status = 1;
                 }
                 
            }
      
         });

如何将道具值带入我的.each() 函数?

【问题讨论】:

    标签: javascript jquery vue.js each


    【解决方案1】:

    this 分配给名为self 的全局变量,然后在$.each 回调中使用它,因为该回调中的this 具有不同的上下文:

      mounted: function(){
    
            let self=this
              
            $.each(this.category_list, function(key, value) {
        
                if(self.active_categories){
        
                  if(self.active_categories.includes(value.ID)){
                       value.Status = 1;
                     }
                     
                }
          
             });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-16
      • 2019-03-19
      • 2021-09-25
      • 2021-11-23
      • 2018-04-26
      • 2020-05-31
      • 1970-01-01
      • 2020-11-15
      相关资源
      最近更新 更多