zoukankan      html  css  js  c++  java
  • Vue.js学习笔记之组件需要注意的地方(一)

    1. data必须是函数,如果是对象的话Vue会停止,并在控制台发出警告,告诉你在组件中data必须是函数。
    2. 当使用的不是字符串模板时,驼峰式命名的prop(js中命名的)在html中使用时要转换成相对应的短横线隔开式命名。比如:
      1 Vue.component('child', {
      2   // camelCase in JavaScript
      3   props: ['myMessage'],
      4   template: '<span>{{ myMessage }}</span>'
      5 })
      1 <!-- kebab-case in HTML -->
      2 <child my-message="hello!"></child>

      否则Vue会停止,并在控制台发出警告:vue.js:491 [Vue tip]: Prop "mymsg" is passed to component <MyComponent>, but the declared prop name is "myMsg". 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 "my-msg" instead of "myMsg".

    3. 不要用字面量语法传递数值:
      1 <!-- 传递了一个字符串 "1" -->
      2 <comp some-prop="1"></comp>

      因为这里的some-prop是字面prop,所以传的1是字符串而不是number.若想传递的是number则需要使用动态语法,即用v-bind,从而让它的值被当作js表达式计算:

      1 <!-- 传递实际的 number -->
      2 <comp v-bind:some-prop="1"></comp>
    4. 在js中对象和数组是引用类型,指向同一个内存空间,如果prop是一个对象或数组,在子组件内部改变它会影响父组件的状态。工作中就遇到这个问题了,把对象或数组类型的prop直接在子组件内部赋给子组件内部定义的局部变量不行,用一个工厂函数把父组件的对象或数组类型的prop返回给子组件的局部变量也不行,最后的解决办法是改完了父组件的对象或数组类型的prop之后,去使用,使用完后,又改了回去(笑cry了,好笨的办法,下边代码的下边有更好的解决办法):
       1 //不要这样赋值:
       2 this.localityConfig=this.config
       3 //这样赋值也不行:
       4 this.localityConfig=this.getConfig();
       5 methods:{
       6   getConfig(){
       7             return this.config;
       8         }  
       9 }
      10 //最后这样弄的:
      11 if(this.isEmptyChart){
      12   this.config.data.datasets[0].data[0]=1;
      13 }
      14 this.myNewChart=new Chart(ctx,this.config);
      15 if(this.isEmptyChart){
      16    this.config.data.datasets[0].data[0]=0;//当this.isEmptyChart为true时就是0,上面改成了1,用完后再改成0
      17 }              

       后来请教了下大神,原来很简单,用jQuery.extend()方法就能解决这个问题,注意一定要让$.extend的第一个参数deep为true。

      1 if(this.isEmptyChart){
      2     let localityConfig=$.extend(true,{},this.config);
      3     localityConfig.data.datasets[0].data[0]=1;
      4     this.myNewChart=new Chart(ctx,localityConfig);
      5 }else{
      6     this.myNewChart=new Chart(ctx,this.config);
      7 }

       用jQuery.extend()方法后改变localityConfig不会影响config。 

    5. 要指定prop验证规格,需要用对象的形式,而不能用字符串数组。指定验证规格时的type可以是一个自定义构造器函数,使用instanceof检测。注意props会在组件实例创建之前进行校验,所以在default或validator函数里,诸如data、computed或methods等实例属性还无法使用。

  • 相关阅读:
    Hadoop- Cluster Setup
    Hadoop- Cluster Setup
    【网络协议】动态主机配置协议DHCP
    【网络协议】动态主机配置协议DHCP
    数据流(任务并行库 TPL)
    数据流(任务并行库 TPL)
    js数据存储.html
    对象操作(2).html
    对象操作(1).html
    对象forin循环.html
  • 原文地址:https://www.cnblogs.com/code2017/p/learning_vuejs_1.html
Copyright © 2011-2022 走看看