Vue组件的边界情况

01.$root;

访问组件的根实例;用的不多,基本上在vuex上进行数据操作;

02.$parent/$children;

可以获得父组件或者子组件上边的数据;一般不建议使用$parent,因为如果获取这个值进行修改的话,也会更改父组件上边的数据;

<template>
    <div>
        //相当于使用了爷组件上边title属性的值
        {$parent.$parent.title}
        <button @click="$parent.$parent.handle">
            调用爷组件上边的方法
        </button>
    </div>
</template>

03.$refs;

这个也可以获取到子组件上边的数据;在el组件中我们可以通过这个来进行验证数据;

this.$refs[formname].validate((valid)=>{
    if(valid){

        console.log('success');

    }else{
        
        console.log('fail')
        return false;
    }

})

//这是子组件
<tempalte>
<div>
    <input v-model="input" type="text" ref="txt">
</div>

</template>

export default{

    data(){

        return{

        input:''
}

},

    methods:{

        fucus(){
        this.$refs.txt.focus()

}

}


}

<template>

    <div>
        <niu ref="hao"/>

        <button @click="huo">获取焦点</button>
    </div>
</template>

import niu from './niu.vue'

export default{

components:{
    niu
},
methods:{

    huo(){

        this.$refs.hao.focus();
        this.$refs.hap.value = '牛啊牛'

    }

}



}

04.provide、inject

嵌套比较多的情况下子组件使用这个好用

//父组件


export default{

    provide:{

        return:{
            title:this.title,
            message:this.message
        }

    },

    methods:{
        message(){
           return this.title
        }
    }

}

//子组件  获得title变量以及message的方法

export default{

    inject:['title','message']


}

05.$attrs

把父组件中非props属性绑定到内部组件(不包含style,class属性)

//子组件


<template>
    <div>

        <input  v-bind="$attrs">

    </div>


</template>

export default{


    inheritAttrs:false

}

06.$listeners

 把组件中DOM对象的原生事件绑定到内部组件

猜你喜欢

转载自blog.csdn.net/2201_75705263/article/details/132253229