vue3中组件的父-->子,子-->父组件的数据共享

477 阅读1分钟

1、父组件 --> 子组件 及 组件间的 v-model 使用

父组件向子组件共享数据时,父组件需要使用 v-bind 属性绑定指令来向子组件共享数据,子组件需要使用 peops 自定义属性来接收父组件共享过来的数据。

<template>
  <h1> APP 根组件 -- {{ counts }}</h1>
  <button @click="counts += 1"> count +1</button>
  <!-- 注册 Son 组件 -- 传递数据给子组件 -->
  <Son :user="users" :age="ages" v-model:count="counts"></Son>
</template>

<script>
import Son from './son.vue'
export default {
  name: 'MyApp',
  data() {
    return {
      users: 'zs',
      ages: 18,
      counts: 0
    }
  },
  components: {
    Son
  }
}
</script>

子组件使用 props 自定义属性 和 插值表达式 {{}} 来接收和展示数据

<template>
  <h1> Son 组件 -- {{ count }}</h1>
  <button @click="addCount"> count +1</button>
  <hr>
  <!-- 展示接收过来的数据 -->
  <p>这是从父组件接收过来的user: {{user}}</p>
  <p>这是从父组件接收过来的age: {{age}}</p>
</template>

<script>
export default {
  name: 'Son',
  // 接收数据
  props: ['user', 'age', 'count'],
  emits: ['update:count'],
  methods: {
    addCount() {
      this.$emit('update:count', this.count + 1)
    }
  }
}
</script>

2、子组件 --> 父组件

子传父需要自定义事件,通过 this.$emit 触发自定义事件 在 vue3 中需要 定义自定义事件的名称,通过 emits 节点来定义 自定义事件的名称

子组件 --

<template>
  <h1>Son 组件 -- {{name}}</h1>
  <hr>
  <button @click="sendInfo"> 传递数据给 父组件</button>
</template>

<script>
export default {
  name: 'Son',
  // 定义自定义事件的名称
  emits: ['reinfo'],
  data() {
    return {
      name: '蜡笔小新'
    }
  },
  methods: {
    sendInfo() {
      this.$emit('reinfo', this.name)
    }
  }
}
</script>

<style lang="less" scoped>
</style>

父组件

<template>
  <h1>App 根组件 -- {{ info }}</h1>
  <hr>

  <Son @reinfo="getData"></Son>
</template>

<script>
import Son from './Son.vue'

export default {
  name: 'MyApp',
  data() {
    return {
      info: ''
    }
  },
  methods: {
    getData(val) {
      this.info = val
    }
  },
  components: {
    Son
  }
}
</script>

<style lang="less" scoped>
</style>