怎么免費(fèi)做一個(gè)網(wǎng)站做淘寶客/站長(zhǎng)平臺(tái)
1. 介紹
概念:通過 ref標(biāo)識(shí) 獲取真實(shí)的 dom對(duì)象或者組件實(shí)例對(duì)象
2. 基本使用
實(shí)現(xiàn)步驟:
-
調(diào)用ref函數(shù)生成一個(gè)ref對(duì)象
-
通過ref標(biāo)識(shí)綁定ref對(duì)象到標(biāo)簽
代碼如下:
父組件:
<script setup>
import { onMounted, ref } from 'vue'import SonCom from '@/components/Son-com.vue'// 獲取元素const titleRef = ref(null)// 修改元素內(nèi)容const updateTitle = () => {titleRef.value.innerText = '我是父組件 agein'}// 渲染完成調(diào)用onMounted(() => {updateTitle()})// 獲取組件const sonRef = ref(null)// 調(diào)用子組件的方法和屬性const getSonMethod = () => {sonRef.value.sonMethod()console.log(sonRef.value.count);}</script><template><div ref="titleRef">我是父組件</div><SonCom ref="sonRef"></SonCom><button @click="getSonMethod">調(diào)用子組件的方法和屬性</button>
</template><style>
</style>
子組件:
<script setup>
import { ref } from 'vue';// 創(chuàng)建子組件屬性
const count = ref(999)// 創(chuàng)建子組件方法
const sonMethod = () => { console.log('子組件方法') }// 暴露方法,父組件可以使用
defineExpose({ count, sonMethod
})</script><template><div>我是子組件</div>
</template><style scoped>
</style>