Vue2中:
$ref
引用信息会注册在父组件的$refs对象上
父组件:
<template>
<div id="app">
<TodoItem ref="msg"></TodoItem>
<p ref="dom"></p>
</div>
</template>
<script>
import TodoItem from './components/so.vue'
export default {
name: 'App',
components: {
TodoItem
},
mounted() {
console.log(this.$refs)
// 通过这种方法给子组件传递数据
this.$refs.msg.getmsg("我是tc") // this.$refs.msg指向的是子组件的实例
console.log(this.$refs.msg.msg)
this.$refs.dom.innerHTML = "我是普通元素"
},
data() {
return {
}
},
}
</script>
<style>
#app {
margin: 20px auto 20px 20px;
}
</style>
子组件:
<template>
<div class="so">
<p>{{ msg }}</p>
</div>
</template>
<script>
export default {
name: "todo-item",
data() {
return {
msg: ''
}
},
methods: {
getmsg(s) {
this.msg = s
}
}
}
</script>
<style scoped>
</style>
Vue3中:
vue3中需要引入defineExpose从子组件向父组件暴露需要获取到的对应的变量或方法
在父组件中可以使用ref="(el) => child = el"的方式来准确获取到子组件的实例,然后使用child.value.(对应方法名或变量名)的方式获取相应信息
父组件:
<template>
<TodoItem :ref="(el) => child = el"></TodoItem>
<p ref="dom"></p>
</template>
<script>
import TodoItem from './components/so'
import { ref, onMounted } from 'vue'
export default {
name: 'App',
components: {
TodoItem
}
}
</script>
<script setup>
const child = ref(null)
// const msg = ref()
const dom = ref()
onMounted(() => {
console.log(child.value.getmsg("我是tc"))
// msg.value.getmsg("我是tc")
dom.value.innerHTML = "我是一个普通的DOM元素"
})
</script>
<style>
#app {
margin: 20px auto 20px 20px;
}
</style>
子组件:
<template>
<div class="so">
<p>{{ msg }}</p>
</div>
</template>
<script>
import { ref, defineExpose } from 'vue'
export default {
name: "todo-item",
}
</script>
<script setup>
const msg = ref("")
const getmsg = (s) => {
msg.value = s
}
// 想要父组件可以获取到需要使用defineExpose向父组件暴露
defineExpose({getmsg})
</script>
<style scoped>
</style>