以上が、Vue3 が ref を通じてサブコンポーネントのインスタンス (サブコンポーネント内の DOM 構造、データ、メソッド) を取得する方法ですが、今日は、index.vue (親コンポーネント) を記述するときに、ref をバインドすることでサブコンポーネントのデータとメソッドを取得したいと考えています。サブコンポーネント。印刷されるサブコンポーネントのデータは未定義です。Baidu 検索の一般的な方法は次のとおりです。
サブアセンブリ
<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>
ref を通じてコンポーネント インスタンスのデータを取得し、未定義として出力するコードは次のとおりです。
親コンポーネント
<template>
<div>
<welcome></welcome>
</div>
</template>
<script setup lang="ts">
import welcome from './welcome.vue'
import { ref,onMounted } from 'vue'
const welcomeRef = ref(null);
console.log("welcomeRef ",welcomeRef.value.isScroll) //welcomeRef undefined
<script>
サブアセンブリ
<template>
<div v-if="isScroll">
测试内容1
</div>
<div v-else>
测试内容2
</div>
</template>
<script setup lang="ts">
import { ref,onMounted } from 'vue'
const isScroll= ref(false);
<script>
情報を確認した結果、次のことがわかりました。
<script setup>
+TSケースに基づく
3つのステップで
1. 親コンポーネントによって呼び出される必要があるプロパティを子コンポーネントで公開します。
2. サブコンポーネントでタイプを定義します
3. 親コンポーネントは子コンポーネントの型を導入し、ref を定義します。
ステップ 1:defineExpose はサブコンポーネントのプロパティを公開します
defineExpose({ select })
ステップ 2: 子コンポーネントでコンポーネント インスタンス タイプを定義します
。最初のステップが完了すると、親コンポーネントが子コンポーネント インスタンスのプロパティを呼び出すと、TS はエラーを報告し、プロパティを見つけることができません (ただし、プロパティには影響しません)。操作)、答えは次のとおりです。サブコンポーネント インスタンスのタイプを宣言するには、タイプを定義する必要があります。
ステップ 3: サブコンポーネントの公開データ型を定義し、
サブコンポーネントの参照を宣言する ref を定義して、サブコンポーネントのインスタンスを取得します (公開属性のみが使用できることに注意してください)