[英]How to get to HTML element of component from another component Vue
您無需通過訪問子html元素來手動設置它們。
如果我理解正確,那么您想執行由父級觸發的子級功能。
一種方法是讓父級具有默認為false的loaded
狀態。 將狀態作為道具傳遞給孩子,然后可以向孩子添加此狀態的手表。 當加載更改為true時,手表應觸發所需的動作。
您可以通過在子代中傳遞一個可以從那里管理的函數或輸入給父代,來使事情復雜化。
但是,正如評論中所提到的,這不必是一個復雜的敘述情況。 我認為父母可以使用isFocused
道具就足夠了。
#1的示例:
在父母中:
<template>
<my-component :isFocused="focusedElement === 'item-1'"/>
</template>
<script>
data () {
focusedElement: null
},
mounted() {
this.focusedElement = 'item-1'
}
</script>
在子/組件中:
<script>
params: ['isFocused'],
watch: {
isFocused(val){
if (val === true) {
this.$refs.input.focus()
}
}
}
</script>
#2的示例:
發出一個功能,你可以在孩子
methods: {
setFocus() { this.$refs.input.focus() }
}
mounted() {
this.$emit('onMounted', this.setFocus);
},
然后,在父級中,您將使用@onMounted
偵聽器注冊該函數。 您仍然需要存儲功能並管理何時從父級啟動功能。 我認為選項一是更好的選擇
在search-payment-component
和ref input
元素中創建方法:
methods: { ... focus() { this.$refs.input.focus() } ... }
並使用this.$refs.searchComponent.focus()
在父組件中調用此方法(是的,還應該引用子組件以使用它)。
將focused
添加到search-payment-component
:
props: ['focused'], ... watch: { focused(val) { val && this.$refs.input.focus() } }
但是,您也應該提供失去焦點的事件作為最佳實踐。
[更新]或者,如果您只想將輸入集中在初始渲染上:
props: { focused: Boolean },
...
mounted() {
focused && this.$refs.input.focus();
}
// in parent template
...
// if you just declared attribute(w/o value) it will be true
<search-payment-component focused ><search-payment-component>
...
另外,如果要在mounted
掛鈎中使用子組件,則應在this.$nextTick
方法中使用它,以確保已渲染子組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.