账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    vue ref 用于v-for的dom元素,出现问题
    • 2020-01-01 00:00
    • 11
    12
    0
    <template>
       <div class="goodList" ref="goodList">
          <dl  class="foodList" v-for="(item, index) in goods" :key="index" ref="foodList">
            <dt class="name">{{item.name}}</dt>
            <dd class="food" v-for="(food, i) in item.foods" :key="i">
              <img :src="food.image" :alt="food.name" width="57" height="57">
            </dd>
          </dl>
        </div>
      </div>
    </template>
    
    <script>
    import axios from 'axios'
    export default {
      methods: {
        // 后台数据
        get_goods () {
          axios.get('/goods')
            .then(res => {
              let { status, data: { errno, data: data2 } } = res
              if (status === 200) {
                if (errno === 0) {
                  this.goods = data2
                  console.log(this.$refs.foodList)  ===>undefined
                  console.log(this.$refs.goodList)  ===><div class="goodList">...</div>
        })
                  this.$nextTick(() => {
                    console.log(this.$refs.foodList) ===><div class="foodList">...</div>
        })
                    console.log(this.$refs.goodList) ===><div class="goodList">...</div>
        })
                  })
                }
              }
            })
            .catch(res => {
              console.log(res)
            })
        }
      },
      created () {
        this.get_goods()
        console.log(this.$refs.foodList)   ===>undefined
        console.log(this.$refs.goodList)   ===>undefined
        this.$nextTick(() => {
          console.log(this.$refs.foodList) ===>undefined
          console.log(this.$refs.goodList) ===><div class="goodList">...</div>
        })
      },
      mounted() {
        console.log(this.$refs.foodList)  ===>undefined
        console.log(this.$refs.goodList)  ===><div class="goodList">...</div>
        this.$nextTick(() => {
          console.log(this.$refs.foodList) ===>undefined
          console.log(this.$refs.goodList) ===><div class="goodList">...</div>
        })
      }
    }

    在网上看到: ref 最好在页面渲染(mounted)以后使用,在页面渲染前(mounted前)使用可以在this.$nextTick()函数中
    有三个疑问:
    1.在created生命周期函数中,this.$nextTick()为什么不能获取v-for的foodList?
    2.在mounted生命周期函数中,页面渲染后,使用和未使用this.$nextTick(),有什么区别? 及this.$nextTick()为什么不能获取v-for的foodList?
    3.在created生命周期函数中,向后台获取数据,使用this.$nextTick(),为什么能获取v-for的foodList
    请各路大神指点指点,非常感谢### 问题描述

    问题出现的环境背景及自己尝试过哪些方法

    相关代码

    // 请把代码文本粘贴到下方(请勿用图片代替代码)

    你期待的结果是什么?实际看到的错误信息又是什么?

    0
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 11 元积分
        全部回答
    • 0
    • 李豫 普通会员 1楼
      502 Bad Gateway

      502 Bad Gateway


      nginx
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部