vue父子间传值

本文详细介绍了Vue.js中父子组件间的通信机制,包括父组件向子组件传递数据的方法及子组件向父组件反馈信息的两种策略,为开发者提供实用的组件间通信解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

搭建项目:本项目使用vue-cli脚手架工具直接搭建
项目结构:
父子组件间传值目录结构

1. 父传子

在父组件调用自组件时,给子组件绑定自定义属性,在子组件中使用props接收,子组件内部直接当成属性使用
父组件调用子组件:

<Son title="hello world" value="test" :city="selectCity"/>

子组件接收:

props: ['title', 'value', "city"],

app.vue

<template>
<div id="app">
  <h1>hello world</h1>

  <Father/>

</div>
</template>

<script>
import Father from './components/Father'
export default {
  components: {
    Father
  }
}
</script>

<style>

</style>

father.vue

<template>
<div class="father">
  <h1>父组件</h1>
  
  <!-- 点击相对应的button子组件中会有相对应的数据变化 -->
  <nav>
    <button v-for="(item, index) in cityList" :key="index"
      @click="selectAction(item)">
      {{item}}
    </button>
  </nav>
  
	<!-- 父组件调用子组件,如果自定义属性是变量时,则需要 :绑定属性  -->
  <Son title="hello world" value="test" :city="selectCity"/>

</div>
</template>

<script>
import Son from './Son'
export default {
  components: {
    Son
  },
  data(){
    return {
      cityList: ['深圳', '广州', '上海'],
      selectCity: ''
    }
  },
  methods: {
    selectAction(city){
      console.log(city);
      this.selectCity = city;
    }
  }
}
</script>

<style scoped>
.father{
  border: 5px solid #ddd;
  padding: 50px;
}
</style>

son.vue

<template>
<div class="son">
  <h1>子组件</h1>

  <p>{{title}}</p>
  <p>{{value}}</p>

<!-- 根据父组件中传过来的City值的变化,以下的数据而变化 -->
  <p>推荐你去玩:</p>
  <ul>
    <li v-for="(item, index) in map[city]" :key="index">
      {{item}}
    </li>
  </ul>

</div>
</template>

<script>
export default {

  // 子组件中使用props接收父组件传过来的值, props也是组件的属性,但是实例没有配置项,属于外部属性
  props: ['title', 'value', "city"],

  // 内部属性
  data(){
    return {
      map: {
        '上海': ['东方明珠', '外滩', '迪斯尼'],
        '深圳': ['世界之窗', '欢乐谷', '千锋'],
        '广州': ['长隆', '广州塔', '千锋']
      }
    }
  }
}
</script>

<style scoped>
.son{
  border: 5px solid #999;
  padding: 50px;
}
</style>
2.子传父(两种方式)
  • 在父组件调用子组件时,给子组件绑定自定义属性, 这个自定义属性是一个函数。
    在子组件内部使用props接收。当需要传值给父组件时,就调用这个属性,通过调用函数传值给父组件。
  • 在父组件调用子组件时,给子组件绑定自定义事件,事件的实现在父组件中,是一个函数。
    当子组件需要传值给父组件时,就使用this.$emit()触发该事件,并传参进去,那么父组件的函数就可以接收到参数了。
第一种方式:

父组件调用子组件:

 <Son :onSend="handleSendAction"/>

函数实现

//函数的实现,也就是传入子组件中的函数,参数为接收子组件传过来的值
    handleSendAction(val){
      console.log('触发了:', val);
      this.arr.push(val);
    }
  }

子组件接收:

 props: {
   onSend: Function
 },

子组件传值触发事件

<!-- 通过button按钮的click触发事件 -->
  <button @click="btnAction">发送</button>
// 通过触发事件,触发父组件传过来的函数
    btnAction(){
      console.log(this.value);
      // 调用父组件的属性,这个属性是一个函数,传入参数为子组件传过去的值
      this.onSend(this.value);
    }
 

father.vue

<template>
<div class="father">
  <h1>父组件</h1>

  <p>接收到了:</p>
  <ul>
    <li v-for="(item,index) in arr" :key="index">
      {{item}}
    </li>
  </ul>

<!-- 父组件调用子组件,绑定一个函数属性,函数在methods中实现 -->
  <Son :onSend="handleSendAction"/>


</div>
</template>

<script>
import Son from './Son'
export default {
  components: {
    Son
  },
  data(){
    return {
      arr: []
    }
  },
  methods: {
  //函数的实现,也就是传入子组件中的函数,参数为接收子组件传过来的值
    handleSendAction(val){
      console.log('触发了:', val);
      this.arr.push(val);
    }
  }
}
</script>

<style scoped>
.father{
  border: 5px solid #ddd;
  padding: 50px;
}
</style>

son.vue

<template>
<div class="son">

  <h1>子组件</h1>

  <input type="text" v-model.lazy="value"/>

<!-- 通过button按钮的click触发事件 -->
  <button @click="btnAction">发送</button>


</div>
</template>

<script>

export default {
//父组件接收,该值为一个函数类型
  props: {
    onSend: Function //确定该值为一个函数
  },
  data(){
    return {
      value: ''
    }
  },
  methods: {
  // 通过触发事件,触发父组件传过来的函数
    btnAction(){
      console.log(this.value);
      // 调用父组件的属性,这个属性是一个函数,传入参数为子组件传过去的值
      this.onSend(this.value);
    }
  }

}
</script>

<style scoped>
.son{
  border: 5px solid #999;
  padding: 50px;
}
</style>
第二中方式:

父组件调用子组件:

 <Son @send="handleSendAction" />

函数实现:

 handleSendAction(val, ...rest){
      console.log('触发了:', val, rest);
      this.arr.push(val);
    }

子组件触发:

<button @click="btnAction">发送</button>
btnAction(){
      console.log(this.value);

      // 触发组件标签上的事件
      // 自定义事件
      // 参数1:自定义事件的名字
      // 参数2:调用事件的参数
      this.$emit('send', this.value, 1, 2, 3);
    }

father.vue

<template>
<div class="father">
  <h1>父组件</h1>

  <p>接收到了:</p>
  <ul>
    <li v-for="(item,index) in arr" :key="index">
      {{item}}
    </li>
  </ul>

  <Son @send="handleSendAction" />


</div>
</template>

<script>
import Son from './Son'
export default {
  components: {
    Son
  },
  data(){
    return {
      arr: []
    }
  },
  methods: {
    handleSendAction(val, ...rest){
      console.log('触发了:', val, rest);
      this.arr.push(val);
    }
  }
}
</script>

<style scoped>
.father{
  border: 5px solid #ddd;
  padding: 50px;
}
</style>

son.vue

<template>
<div class="son">

  <h1>子组件</h1>

  <input type="text" v-model.lazy="value"/>

  <button @click="btnAction">发送</button>


</div>
</template>

<script>

export default {

  data(){
    return {
      value: ''
    }
  },
  methods: {
    btnAction(){
      console.log(this.value);

      // 触发组件标签上的事件
      // 自定义事件
      // 参数1:自定义事件的名字
      // 参数2:调用事件的参数
      this.$emit('send', this.value, 1, 2, 3);
    }
  }

}
</script>

<style scoped>
.son{
  border: 5px solid #999;
  padding: 50px;
}
</style>
### Vue.js 父子组件的数据递方法 #### 使用 `props` 进行数据递 在 Vue.js 中,父组件可以利用 `props` 向子组件递数据。这种方式使得子组件能够接收来自父组件的信息并将其视为只读属性使用。 例如,在定义子组件时指定接受的 prop: ```html <template> <div> <h1>{{ title }}</h1> </div> </template> <script> export default { name: 'ChildComponent', props: { title: { type: String, required: true } } }; </script> ``` 当创建父组件模板并向其中嵌入上述子组件时,则可通过如下形式设置子组件的具体[^3]: ```html <!-- Parent Component --> <template> <div class="parent"> <!-- Passing a string to the child component's prop --> <ChildComponent :title="'Hello from parent'" /> </div> </template> ``` #### 利用 `$refs` 访问子组件实例 除了通过 `props` 单向流动的方式外,还可以借助于 `$refs` 来获取特定子组件的引用,并调用其内部的方法或者修改状态。 考虑这样一个场景——假设有一个名为 `Child` 的子组件拥有一个公开的方法叫做 `hello()`: ```javascript // 子组件 (child.vue) data() { return { name: "child.vue" }; }, methods: { hello() { console.log("hello JS"); } } ``` 那么可以在父级组件里像这样操作这个子组件对象: ```html <!-- Parent Component Template --> <template> <div class="parent"> <Child ref="myChild"/> </div> </template> <script> export default { mounted(){ const myChildInstance = this.$refs.myChild; // 调用子组件中的方法 myChildInstance.hello(); }} </script> ``` 这种方法允许更灵活的操作,但应当谨慎使用以免破坏单向数据流原则[^2]. #### 事件驱动模式下的双向沟通 为了使子组件能通知到父组件某些事情的发生(比如点击按钮),通常会采用自定义事件的形式来进行反向通讯。这涉及到两个方面的工作:一是子组件触发事件;二是父组件监听这些事件以便作出响应。 对于简单的交互来说,可以直接绑定原生 DOM 事件处理器至子组件上,而对于复杂一点的情况则可能需要用到 `.sync` 或者 Vuex store 来管理共享的状态变化[^4]. 综上所述,Vue.js 支持多样的父子组件的通信手段,开发者可以根据实际需求选择最合适的技术方案来构建应用逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值