Vue组件的边界情况

01.$root;

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

02.parent/children;

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

javascript 复制代码
<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;
    }

})
javascript 复制代码
//这是子组件
<tempalte>
<div>
    <input v-model="input" type="text" ref="txt">
</div>

</template>

export default{

    data(){

        return{

        input:''
}

},

    methods:{

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

}

}


}
javascript 复制代码
<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

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

javascript 复制代码
//父组件


export default{

    provide:{

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

    },

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

}
javascript 复制代码
//子组件  获得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对象的原生事件绑定到内部组件

相关推荐
亿元程序员7 分钟前
Cocos4开源都快半年了,还有不会用官方MCP的?安排!
前端
早點睡3907 分钟前
ReactNative项目OpenHarmony三方库集成实战:react-native-inappbrowser(也可以考虑WebView)
javascript·react native·react.js
北风toto9 分钟前
Vue多文件学习项目综合案例——面经基础版,黑马vue教程
javascript·vue.js·学习
奔跑的呱呱牛1 小时前
xlsx 已停止维护且存在漏洞!推荐一个可直接替代的 npm 库
前端·npm·node.js·xlsx·sheetjs
珑墨1 小时前
pnpm 与 node_modules:硬链接、软连接(符号链接)、Junction 速记
前端
浪扼飞舟1 小时前
WPF输入验证(ValidationRule)
java·javascript·wpf
freewlt1 小时前
Monorepo 架构下的前端工程化实践:pnpm + Turborepo 从入门到落地
前端·arcgis·架构
徐小夕9 小时前
我用 AI 撸了个开源"万能预览器":浏览器直接打开 Office、CAD 和 3D 模型
前端·vue.js·github
小码哥_常9 小时前
Flutter Android 延迟加载代码指南:提升应用性能的关键
前端
这是个栗子9 小时前
TypeScript(三)
前端·javascript·typescript·react