最近在做项目的过程中遇到一个问题,我们创建自己的组件时,父组件传给子组件一个数组,子组件使用v-for指令无法渲染,以下是错误代码:

Vue.component('component-test',{
    props: {
      testData: {
        type: Array,
        default: []
      }
    },
    template: '<li v-for="(item,index) in testData">{{item}}</li>'
 })

当我们使用watch监听testData变化时发现testData的值已经改变,但页面上却没有响应渲染出对应的元素。

但如果给模板(template)套上一个父元素,再使用v-for时,发现又可以成功渲染了,成功代码如下:

Vue.component('component-test',{
    props: {
      testData: {
        type: Array,
        default: []
      }
    },
    template: `<ul>
                    <li v-for="(item,index) in testData">{{item}}</li>
               </ul>`
})

以上的区别也就是在v-for元素上加一个父元素套起来而已,然而其中的原理至今尚未明白,百思不得解。哪位大神知道原因的劳烦告知,感谢!!!

Logo

前往低代码交流专区

更多推荐