Vue中在指令v-bind中使用驼峰命名后,数据渲染失败

  1. 代码如下,父组件给子组件child-module传值的时候,由于v-bind的自定义属性childProperty使用的是驼峰命名而导致子组件中的数据渲染失败。
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body> 
<div id="app">
  Hello :  
  <child-module v-bind:childProperty="parentProperty"></child-module>
</div>
</body>
<script>
Vue.component('child-module',{
    props: ['childProperty'],
    template : '<li>child property is : {{childProperty}}</li>',
});
var app = new Vue({
  el: '#app',
  data: {
    parentProperty: 'hello childs',
  }
});
</script>
</html>
  1. 运行结果如下,并不是期待的 child property is : hello childs.
    在这里插入图片描述
  2. 查看浏览器控制台得到如下信息。
    Prop “childproperty” is passed to component , but the declared prop name is “childProperty”. Note that HTML attributes are case-insensitive and camelCased props need to use their kebab-case equivalents when using in-DOM templates. You should probably use “child-property” instead of “childProperty”.

Vue提示我们说属性名字是childPropery, 但是HTML属性是大小写不敏感的,所以推荐我们使用中划线的方式,也就是child-property 来替换驼峰式命名。

  1. 查找Vue 2.X 官方文档给出的解释是:在 DOM 中使用模板时 (直接在一个 HTML 文件里撰写模板),还需要避免使用大写字符来命名键名,因为浏览器会把 attribute 名全部强制转为小写。
    在这里插入图片描述 分析如下,因为浏览器不区分大小写,并且浏览器会把字符串都转换为小写字符再去解析;所以childProperty被转换为childproperty, 然后再去子组件props里面去寻找,如下。当然没找到,所以子组件中的数据被渲染失败,输出为空。
Vue.component('child-module',{
    props: ['childProperty'],
    template : '<li>child property is : {{childProperty}}</li>',
});
  1. 解决办法只需要按照Vue推荐的去将驼峰命名childProperty转换为中划线child-property的形式即可。
    Vue首先会将child-property解析为childProperty,然后再去props里面找,结果就能找到。
    只需要修改html,script里面保持不变。
<div id="app">
  Hello :  
  <child-module v-bind:child-property="parentProperty"></child-module>
</div>
  1. 更改后再次运行为:
    在这里插入图片描述
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值