Vue框架学习三

今天主要是了解Vue框架的细节,父子组件的传值过程,以及传值过程中的参数校验。看完视频后。理解了代码的结构,能够自主的完成代码的敲打,感觉熟练了一点。同时在过程中的小bug,及时改正。下面说一下三点内容。

4-1,模板组件细节知识点
   (1)H5中table -tbody tr ,使用is属性:is=row,
   (2)根组件中data中可以是对象,子组件data中必须是个函数,返回该对象。
   is使用解决的是是Dom层结构符合H5的语法结构。

<div id="root">
	<table>
	   <tbody>
	   	<tr is="row"></tr>
	   </tbody>	
	</table>
</div>
<script>
    Vue.component("row",{
    	data:function(){
    		return {
    			content:"热爱 data",
    		}
    	},
    	template:'<tr><td>{{content}}</td></tr>'
    })
	var vm = new Vue({
		el:"#root",
	})
</script> 
ref,组件中加上ref,获取到组件的引用,子组件通过事件监控传递数据到父组件。实现加法
这里添加ref可以获取到<counter>的属性、

<div id="root">
<counter ref="one" @change="handleChange"></counter>
<counter ref="two" @change="handleChange"></counter>
<div>{{total}}</div>
</div>
<script>
Vue.component("counter",{
	data:function(){
		return {
			number:0
		}
	},
	template:'<div @click="handleClick">{{number}}</div>',
	methods:{
		handleClick:function(){
			this.number++;
			//子组件受父组件监听
			this.$emit('change')
		}
	}
})
var vm = new Vue({
	el:"#root",
	data:{
		total:0,
	},
	methods:{
		handleChange:function(){
			this.total=this.$refs.one.number + this.$refs.two.number;
			//alert(this.$refs.one.number);
		}
	}
})
</script>
4-2父子组件之间的传值。
 

   子组件中props:['count']接收父组件的参数对象。
   这里子组件向父组传值采用事件监控,传递变化参数2,没有引用ref

 div id="root">
<counter  @change="changeClick" :count='3'></counter>
<counter @change="changeClick" :count='2'></counter>
<div>{{total}}</div>
</div>
<script>
var counter={
  props:['count'],//接收父组件中的count
  data:function(){
  	return{
  		number:this.count
  	}
  },
  template:'<div @click="handleclick">{{number}}</div>',
  methods:{
  	handleclick:function(){
  		this.number=this.number+2;
  		this.$emit('change',2);
  	}
  }
}
var vm=new Vue({
el:"#root",
components:{
	counter:counter,
},
data:{
	total:5
},
methods:{
	changeClick:function(step){
		//this.total=this.$refs.one.number+this.$refs.two.number
	   console.log(step);
	   this.total=step+this.total;
   }
}
	
})
</script>

4-3组件参数校验:
    限定父组件传到子组件可以使数字或者字符串,对象。

    props:{
        count:[Number,String]
    },可以限制传入的参数是数字或者字符串

props:{
    count:{
    type:String,
//    required:true,判断是否类型正确
        //default:"lvzekun",默认参数
        validator:function(value){设置校验器,如字符串长度
               return (value.length>5)
        }
    }
},
 

注意事项;$refs的使用,子组件中data:{},必须是函数,返回对象

父组件传值,子组件props接收子组件,定义新对象用于参数变化,设置监听事件$emit(),父组件监听事件,返回函数处理。

猜你喜欢

转载自blog.csdn.net/m0_37727198/article/details/81871432