作者:膈应人的ID | 来源:互联网 | 2022-12-02 18:27
我需要一种可靠的方法来在vuejs中调用n个父级的父级组件。在jQuery中寻找更像closet('element')的东西时,您不必指定有多少个父母或孩子,只需给它指定所需组件的名称,它将为您递归查找直到它找到合适的。
我只是想知道是否有这样的东西:this。$ find(component-name); 或this。$ closest(component-name);
我在某人正在使用$ ref的地方阅读过,但我认为这不是该用例的正确选择,还是这样?
当您不知道有多少父母时,显然不是那么可靠的this。$ parent。$ parent。
谢谢,
1> Ricky..:
您可以使用while循环,遍历所有父组件。
getComponent(componentName) {
let compOnent= null
let parent = this.$parent
while (parent && !component) {
if (parent.$options.name === componentName) {
compOnent= parent
}
parent = parent.$parent
}
return component
},
例:
mounted() {
console.log(this.getComponent('App'))
},
实用功能(TS):
import Vue from 'vue'
/**
* @name findParentComponentByName
* @summary Find the Vue instance of the first parent component that matches the provided component name.
*
* @description The `findParentComponentByName()` method returns the Vue instance of the first parent component
* that has a `name` component option that matches the provided component name.
*
* @param {Vue} vm - The children component Vue instance that is looking for the parent component Vue instance
* @param {string} componentName - The parent component name
* @returns {Vue|undefined} The parent component instance that matches the provided component name,
* otherwise, undefined is returned
*
* @example
* // Find `` component from ``:
*
*
*
*
*
*
*
*
* // Descendant component Vue instance
* new Vue({
* name: 'Child',
*
* created() {
* const app = findParentComponentByName(this, 'App')
* // => VueComponent {_uid: 1, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …}
* },
* })
*/
export function findParentComponentByName(
vm: Vue,
componentName: string
): Vue | undefined {
//
// Components tree:
// +---------------------+ \ return undefined, , is not a descendant of \
// | |---> Return if component name option matches, otherwise
// |---------------------| \ continue traversing the tree upwards \
// | |-----> Return if component name option matches, otherwise
// |---------------------| \ continue traversing the tree upwards \
// | |-------> Return if component name option matches, otherwise
// |---------------------| \ traverse the tree upwards \
// | |---------> STARTING POINT, start looking for App component from here
// |---------------------|
// | |
// |---------------------|
// | |
// |---------------------|
// | |
// +---------------------+
//
let component: Vue | undefined
let parent = vm.$parent
while (parent && !component) {
if (parent.$options.name === componentName) {
compOnent= parent
}
parent = parent.$parent
}
return component
}
例:
// In consuming component
import { findParentComponentByName } from '@/utils'
// ...
mounted() {
console.log(findParentComponentByName(this, 'App'))
},