<!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">
<title>Document</title>
</head>
<body>
<div id="app">
<h1>{{rootMesage}}</h1>
<child1-component></child1-component>
<child2-component></child2-component>
</div>
<script src="./vue.js"></script>
<script>
// 每个组件都有一个独立的作用域,组件之间不能直接访问对方的数据
// 父子组件之间是相互独立的,不能访问对方的数据(组件的状态)
// 兄弟组件之间是相互独立的,不能访问对方的数据(组件的状态)
const app = new Vue({
el: '#app',
data: {
rootMesage: 'app根组件的数据'
},
mounted() {
// 使用实例的 $children 属性获取所有的子组件
console.log(this.$children)
// 根据索引获取特定的子组件
console.log(this.$children[0].child1Message)
console.log(this.$children[1].child2Message)
},
components: {
'child1-component': {
data () {
return {
child1Message: 'child1组件的数据'
}
},
mounted () {
// 使用组件实例的 $parent 属性获取父组件
console.log(this.$parent.rootMesage)
},
template: '<div><h2>{{child1Message}}</h2></div>'
},
'child2-component': {
data () {
return {
child2Message: 'child2组件的数据'
}
},
template: '<div><h2>{{child2Message}}</h2></div>'
}
}
});
</script>
</body>
</html>
组件基础-通过组件的关系进行访问 this.$children this.$parent
猜你喜欢
转载自blog.csdn.net/qq_45802159/article/details/103818258
今日推荐
周排行