vue中父子组件之间的传值总结

父子组件间传值

其一:父组件向子组件传值

第一种方式:用props父组件嵌套的子组件中。

使用v-bind:msg=‘xxxx’进行对象的绑定,子组件中通过定义props接收对应的msg对象。

父组件代码

<template>
  <div>
    <!-- 注意  :msg 后面是一个对象,值是字符串时,需要写冒号,如果省略:就是一个字符串 -->
    <!-- <m-child msg="from Parent msg" ></m-child> -->
    <m-child v-bind:msg="'from Parent msg'" ></m-child>
  </div>
</template>

<script>
// 引入子组件
import MChild from './Child'
export default {
  data () {
    return {
      msg: ''
    }
  },
  components: {
    MChild,
  },

子组件代码

<template>
  <div>
    <h5>{{msg}}</h5>
  </div>
</template>

<script>
export default {
  // 要接受父组件传递的参数
  props: {
    msg: {
      type: String,
      default: ''
    },
  },

第二种方式:使用$children获取子组件和父组件对象

父组件代码:

 this.msg2=this.$children[0].msg

第三种方式:使用$ref获取指定的子组件

父组件代码:

  <m-child v-bind:msg="p2C" @showMsg='getChild' ref='child'></m-child>
  this.c2P=this.$refs.child.msg33

其二:子组件向父组件传值

第一种方式:使用$emit传递事件给父组件,父组件监听该事件

子组件代码

<button @click="pushMsg()"></button>
  methods: {
    pushMsg() {
      this.$emit("showMsg", "这是子组件===>父组件的值");
    }
  },

父组件代码

<m-child v-bind:msg="p2C" @showMsg='getChild' ref='child'></m-child>
  methods: {
        getChild(val) {
            this.msg=val
        },
}

第二种方式:使用$parent.获取父组件对象,然后再获取数据对象

子组件代码

  mounted() {
    this.msg22 = this.$parent.msg2;
  }
Vue 3 父子组件之间的数据递主要有以下几种方式: 1. **props** (属性绑定): 父组件通过 props 向子组件递数据。父组件将数据作为属性递给子组件,然后在子组件内通过 prop 的名称来接收这个数据。这是单向的数据流,防止了修改父组件的状态。 ```javascript // 父组件 <template> <child-component :value="parentValue"/> </template> <script> export default { data() { return { parentValue: 'default value' }; }, }; </script> // 子组件 <template> <div>{{ value }}</div> </template> <script> export default { props: ['value'], }; </script> ``` 2. **自定义事件($emit/$on)**: 如果需要双向绑定,或者在子组件状态改变时通知父组件,可以使用自定义事件 $emit 和 $on。子组件触发 `$emit('some-event', data)`,父组件监听并处理这个事件。 ```javascript // 父组件 <template> <child-component @childEvent="handleChildEvent" /> </template> <script> methods: { handleChildEvent(data) { this.parentValue = data; } } </script> // 子组件 <template> <button @click="$emit('childEvent', newValue)">Change Value</button> </template> ``` 3. **ref 和 computed** (引用属性和计算属性): 当需要在子组件内部访问或修改递过来的数据时,可以使用 ref。如果需要基于子组件的数据动态计算出新的,可以用 computed。 ```javascript // 父组件 <template> <child-component :value="parentValueRef.value" /> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, setup() { const parentValueRef = ref(''); // ... }, }; </script> // 子组件 <template> <input v-model="localValue" @input="$emit('update:value', localValue)"> </template> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值