首页 > 其他分享 >Vue的父子传值方法

Vue的父子传值方法

时间:2022-10-29 23:23:21浏览次数:47  
标签:Vue 自定义 模板 父子 num 事件 组件 data 传值

Vue的父子传值方法

子传父

要点:通过自定义事件触发父级方法来进行修改父级数据

总结:

1.在父组件中定义修改数据方法

2.在模板中绑定触发自定义事件的事件

3.调用子组件的时候,使用自定义事件绑定父组件方法

知识点:this.$emit("自定义事件名",自定义事件绑定的事件函数的参数)

步骤:

1.声明子组件

new Vue({
el:"#app",
data:{
fatherNum:20
},
components:{
child:{
            template:'#tmpl',
            data(){
            return{
step:20    //写下定义的需要为的数据
}},}},
}})

 

2.在需要修改到父组件数据的地方,触发这个自定义事件(fn一旦触发,chanFatherNum就会执行)

子级用this.$emit调用父级的方法

new Vue({
el:"#app",
data:{
fatherNum:20
},
components:{
child:{
            template:'#tmpl',
            //写下定义的需要为的数据
            data(){ return{  step:20 }
methods:{
               //在子级中声明方法
hdClick(){
this.$emit("fn",this.step)
}}}}
}})}}

$emit() 专门用来触发自定义事件

this.$emit("事件名",事件函数的参数)

子组件中通过事件进行触发传递

<template id="tmpl">
   <div>
       <p>{{num}}</p>
       <button @click="hdClick">按钮</button>
   </div>
</template>

 

3.在父组件中,通过自定义事件,绑定事件函数的方式,接收这个函数**

<div id='app'>
   <p>父组件中的数字是: {{fatherNum}}</p>
   <!-- 2.在父组件中,通过自定义事件,绑定事件函数的方式,接收这个函数 -->
   <!--!!注意!! @fn 是自定义事件 !! -->
   <child :num="fatherNum" @fn="chanFatherNum"></child>
</div>  
<SCRIPT>
// 单向数据流(父组件不允许子组件直接修改父组件的数据)

 

4.在父组件中定义一个修改数据的方法**

new Vue({
el:"#app",
data:{
fatherNum:20
},
components:{
child
},
// 定义修改数据的方法
methods:{
       //形参携带上了子组件传递而来的参数
chanFatherNum(val){
this.fatherNum+=val
}
}})

 

子传父需要注意的点

  1. 修改到父组件的时候有专门的方式 -- 子传父

  2. this.num这种方式只用于获取数值而无法产生改变

  3. $emit() 专门用来触发自定义事件

  4. 父组件中定义用于接收数据的方法的形参携带上了子组件传递而来的参数

 

 

父传子

1.在父组件内部,声明这个标签属性,用来接收父组件的数据

new VUe({
el:"#app",
data:{
fatherNum:20 //父组件的数据
},
components:{
       //注册子组件
child:{
           //子组件通过ID对模板进行绑定
           template:"#tmpl", //指定模板
           props:["num"] // 1. 声明标签属性
           
           data:(){}
      methods:{}
  }}})

亦可以通过使用对象来接收子组件参数

let child = {
template:"#tmpl", //指定模板
props:["num"] // 1. 声明标签属性
}

new VUe({
el:"#app",
data:{
fatherNum:20 //父组件的数据
},
components:{
       //注册子组件
child:{
  }}})

1.5声明标签的两种接收形式

//数组形式
props:["num","age"]
//对象形式
props:{
   num:{
       type:Sting,
       default:"默认值"
  },
   age:{
       type:Number,
       default:"默认值"
  }}

对象形式接收类型与默认值

 

2在父组件调用子组件的时候,用标签属性 接收 父组件的数据

<div id='app'>
   <child :num="fatherNum"></child>
</div>  

3.在子组件模板中通过标签属性调用数据

// 子组件中准备模板
<template id="tmpl">
   <div>
       <p>{{num}}</p>
   </div>
</template>

 

子传父需要注意的点

  1. 子组件需要用ID对模板进行绑定

  2. 模板与根级div同级

  3. 子组件可以拥有自己的方法与函数

  4. 需要使用props:["num"]与props:{ num: {} } 其中一种方法进行绑定

  5. 对象形式中数据接收类型与默认值 

标签:Vue,自定义,模板,父子,num,事件,组件,data,传值
From: https://www.cnblogs.com/Dollom/p/16840189.html

相关文章