vue中父组件使用props或者$attras向子组件中传值

知识点:vue中使用props或者$attras向子组件中传值

  (1) props传值

子组件必须注册好要传的数据()

 props:['id']

(2)$attrs传值

  该数据在props中,没有注册过,如注册过了,则$attrs中无此数据

父组件

<div id="parent" v-cloak>

       <template>
          <mychild :id="id"  :strname="strname"  :age="age" ></mychild>
      </template>

</div>
<script>
new Vue({
el: '#parent',
data:function() {
return {

id:1001,
strname:'名称',
age:25
}
},
});
</script>

子组件
var html_mychild =
+ "   <div>\n"
....页面内容
+ "  </div>\n"
Vue.component('mychild', {
template: html_mychild,
props: ['id'], //1. props传值,注册id,id和:id="id" 冒号后面的id名称一样
data: function () {
return {
id:this.id

}
},
created: function () {
var id=this.id;//获取父组件传过来的,props注册过的id值
var attr=this.$attrs;//获取父组件传过的所有的,并且不再props中注册过的值
var name = this.$attrs.strname;
},
});
 

猜你喜欢

转载自www.cnblogs.com/shuaifing/p/10870591.html