前端知识学习

  • 子组件
<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <input type="file" id="fileInput" name="file" multiple="multiple" @change="selectFile"/>
  </div>
</template>
 
<script>
import { defineComponent, ref } from 'vue'
export default defineComponent({
  name: 'HelloWorld',
  setup() {
    const msg = ref('HelloWorld') // 响应式数据:msg
    const fileList = ref([]) // 响应式数据:上传的文件列表
    function selectFile () { // 有文件上传时
      var file = document.getElementById('fileInput').files[0] // File(Blob) 对象   File extends Blob
      fileList.value.push(file)
    }
    return { // return中的数据会被父组件拿到
      msg,
      fileList,
      selectFile
    }
  }
})
</script>
 
  • 父组件
<template>
  <div class="home">
    <HelloWorld ref="sonRef" />
    <button @click="getSonComponent">GetSonComponent</button>
  </div>
</template>
 
<script>
import { defineComponent, ref } from 'vue'
import HelloWorld from '@/components/HelloWorld.vue'
 
export default defineComponent({
  name: 'Home',
  components: {
    HelloWorld
  },
  setup(){
    const sonRef = ref(null) // 通过 ref 绑定子组件
    function getSonComponent () { // 通过 ref 获取子组件\
      // 获取子组件的数据
      console.log(sonRef.value)
      console.log(sonRef.value.msg)
      sonRef.value.fileList.forEach(item => {
        console.log(item)
      })
    }
    return {
      sonRef,
      getSonComponent
    }
  }
})
</script>