Vue3:父子传值

564 阅读1分钟

1、props 和 emit 方式

需求: 父子传值:子组件接收父组件的值并绑定到table上;子组件双击行数据,传递该行数据给父组件,并打印出来。

父组件代码:

<template>
    <hr>
    <div>
      {{ rowObj }}
    </div>
    <hr>
    <al-table :table-data="tableData" @dbRowClick="dbClick"/>
</template>
<script>
import AlTable from '@/components/AlComponents/AlTable.vue'
import {onMounted, reactive, ref, toRefs, provide} from "vue";

export default {
  components: {AlTable},
  setup() {
    const tableData = reactive([
      {
        date: '2016-05-03',
        name: '王小虎',
        province: '上海',
        city: '普陀区',
        address: '上海市普陀区金沙江路 1518 弄',
        zip: 200333,
      },
      {
        date: '2016-05-07',
        name: '王小虎',
        province: '上海',
        city: '普陀区',
        address: '上海市普陀区金沙江路 1518 弄',
        zip: 200333,
      }
    ]);

    const msg = ref('这是一个message信息') 

    let state = reactive({
      rowObj: {}  // 单行数据
    })

    const dbClick = (val) => {
      console.log('子组件传来的值')
      state.rowObj = val
    }
  
    // onMounted方法
    onMounted(() => {
      tableData.forEach(item => {
        item['show'] = false
      })
    })

    return {
      tableData,
      dbClick,
      ...toRefs(state) // 对响应式对象解构
    }
  }
}
</script>

子组件代码:

<template>
  <div>
    <el-table
        :data="tableData"
        @row-dblclick="dbRowClick"
        style="width: 100%">
      <el-table-column type="index"></el-table-column>
      <el-table-column prop="date" label="日期" width="180"></el-table-column>
      <el-table-column prop="name" label="姓名" width="180"></el-table-column>
      <el-table-column prop="address" label="地址"></el-table-column>
    </el-table>
  </div>
</template>

<script>
import {toRefs, inject} from 'vue'

export default {
  name: "AlTable",
  props: {
    'tableData': {
      type: Array,
      default: []
    }
  },
  setup(props, {emit}) {
    const {tableData} = toRefs(props) // 打印父组件传递的值

    const dbRowClick = (row) => {
      emit('dbRowClick', row)  // 使用emit传递数据到父组件
    }

    return {
      tableData,
      dbRowClick,
      name
    }

  }
}
</script>

<style scoped>

</style>

2、provide 和 inject 方式

父组件中使用provide方式: provide('name', '章三'); 在子组件以及子孙后代中,inject('name')来获取到值;