Vue组件以及props

659 阅读2分钟

Vue 父子数据传递

写在前面

最近在学习Vue,为了深入理解Vue的组件传值,写了一个demoVue的一些原理进行了分析。在使用props以及自定义组件进行传值实验时主要遇到过如下两个主要的问题。

练习Vueprops传递数据没有使用Vue-Cli脚手架。

  1. [Vue warn]: Unknown custom element: <son-container>无法识别自定义组件。
  2. [Vue warn]: Property or method "son" is not defined on the instance but referenced during render. 以及[Vue warn]: Property or method "title" is not defined on the instance but referenced during render. 不能使用子组件自定义的props

Vue生命周期对props传值的影响

[Vue warn]: Unknown custom element: <son-container>关于为何子组件无法加载的问题。

检查组件代码

JS部分
    var vm = new Vue({
        el: "#father-container",
        data: {
            title: "父组件数据"
        }
    })

    Vue.component("son-container", {
        props: ['son-title'],
        template: '<h3>{{son-title}}</h3>',
    })
HTML
    <div id="father-container">
        父组件
        <son-container :son-title="title"></son-container>
    </div>

首先检查了自定义组件的源码,并没有解决问题,期间尝试了很多解决办法无果,最终参考了博客[Unknown custom element: <xxx>](Unknown custom element: <xxx> - did you register the component correctly?错误解决方法_谁都不许动我的砖的博客-CSDN博客),解决了问题。

    // 将 Vue.component 与 new Vue实例对换了位置。
    Vue.component("son-container", {
        props: ['son-title'],
        template: '<h3>{{son-title}}</h3>',
    })

    var vm = new Vue({
        el: "#father-container",
        data: {
            title: "父组件数据"
        }
    })
为什么调换了JS代码顺序后问题得到了解决。

出现这个问题的原因是组件并未注册,而这个时候父组件的vue实例是加载的,JS是从上到下执行的,所以猜测和Vue生命周期以及JS的执行原理有关。等日后对源码理解精进了再来继续解读。

代码规则对Vue传值的影响

解决了Unknown custom element: <xxx>以后,又出现了前言中 2 的问题。

微信图片_20211018133212.png 很迷惑,为什么会出现 props 无法传参的问题

即使是将 props 参数替换为常量依然无法赋值给 son-title

解决思路

  1. 出现了两个警告,是因为找不到 Property or methodsontitle
  2. 猜测没有将我哦设置的 props 当成一个独立的整体。尝试用小驼峰去命名 JS部分程序
JavaScript 部分的 props 命名以 小驼峰规则 命名
    Vue.component("son-container", {
        props: ['sonTitle'],
        template: '<h3>{{sonTitle}}</h3>',
    })

问题的到了解决,控制台输入 vm.title = "你好啊!子组件",发现 <son-container>组件显示数据随着变化。

最后放上Vue官方文档的风格指南--Vue.js