vue中$root访问根组件、$parent和$emit访问父组件、$ref访问子组件
vue中$root访问根组件、$parent和$emit访问父组件、$ref访问子组件
·
一、$root
访问根组件中的属性或方法
- 注意:是根组件,不是父组件。
$root
只对根组件有用。
this.$root.genMethod();//genMethod()是根组件中的方法名
this.$root.genName;//genName是根组件data中的属性名
- 完整示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<title>$root访问根组件中的属性或方法</title>
</head>
<body>
<div id="app">
<com1></com1>
</div>
<script>
var vm = new Vue({
el: "#app",
data() {
return {
rootInfo:"我是根元素的属性"
}
},
methods: {
alerts() {
alert(111)
}
},
components: {
com1: {
data() {
return {
info: "组件1"
}
},
template: "<p>{{ info }} <com2></com2></p>",
components: {
com2: {
template: "<p>我是组件1的子组件</p>",
created() {
this.$root.alerts()//111
console.log(this.$root.rootInfo)//我是根元素的属性
}
}
}
}
}
});
</script>
</body>
</html>
二、$parent
或$emit
访问父组件中的属性或方法
$parent
方法,【推荐】
this.$parent.fatherMethod();//fatherMethod()是父组件中的方法名
this.$parent.fatherName();//fatherName()是父组件data中的属性名
$emit
方法。【只能访问父组件中的方法,不能访问父组件中的属性】
<!-- 父组件代码,渲染子组件 -->
<Child @setValue="valueFn" />
<script>
export default{
method:{
valueFn(value) {}
}
}
</script>
<!-- 子组件代码 -->
<script>
this.$emit('setValue', '参数')
</script>
三、$ref
访问子组件中的属性或方法
<Child ref="fun"/>
<script>
this.$refs.fun.childMethod(); //childMethod()是子组件中的方法名
this.$refs.fun.childName; //childName()是子组件中的方法名
</script>
更多推荐
已为社区贡献3条内容
所有评论(0)