簡體   English   中英

如何從另一個組件Vue進入組件的HTML元素

[英]How to get to HTML element of component from another component Vue

這是情況。 有一個內部使用搜索欄組件(cmp2)的組件(cmp1)。 我的目標是深入研究cmp2並在cmp1渲染時抓取input元素以將焦點放在該元素上。 如何使用Vue實現它? 到目前為止,我嘗試過的工作是在cmp2上設置ref ,而不是通過this.$refs.search.$el.firstChild[0].focus()但是我意識到這不是一個選擇。 所以,也許您會幫我解決這個問題。 附有一些屏幕截圖。 非常感謝! CMP1 cmp-2搜索組件,我需要深入了解

您無需通過訪問子html元素來手動設置它們。

如果我理解正確,那么您想執行由父級觸發的子級功能。

  1. 一種方法是讓父級具有默認為false的loaded狀態。 將狀態作為道具傳遞給孩子,然后可以向孩子添加此狀態的手表。 當加載更改為true時,手表應觸發所需的動作。

  2. 您可以通過在子代中傳遞一個可以從那里管理的函數或輸入給父代,來使事情復雜化。

但是,正如評論中所提到的,這不必是一個復雜的敘述情況。 我認為父母可以使用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偵聽器注冊該函數。 您仍然需要存儲功能並管理何時從父級啟動功能。 我認為選項一是更好的選擇

  1. search-payment-component和ref input元素中創建方法:

     methods: { ... focus() { this.$refs.input.focus() } ... } 

    並使用this.$refs.searchComponent.focus()在父組件中調用此方法(是的,還應該引用子組件以使用它)。

  2. 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM