1子组件访问父组件,$parent使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title-hellovuejs</title>
</head>
<body>
<!-- 父组件模板 -->
<div id ="app">
<cpn></cpn>
</div>
<!-- 子组件模板 -->
<template id="cpn1">
<div>
<h2>我是cpn组件</h2>
<ccpn></ccpn>
</div>
</template>
<template id="ccpn">
<div>
<h2>我是子组件</h2>
<button @click="btnClick">按钮</button>
</div>
</template>
<script src="../js/vue.js"></script>
<script>
//1、2父组件中直接创建子组件--root组件
const chen1 = new Vue({
el: '#app', //用于挂载要管理的元素
data:{//定义数据
message: '你好啊'
},
components:{
cpn:{
template: '#cpn1',
data(){
return{
name: '我是cpn组件的name'
}
},
components:{
ccpn:{
template: '#ccpn',
methods:{
btnClick(){
//1.访问父组件$parent
console.log(this.$parent);
console.log(this.$parent.name);
}
}
}
}
}
}
})
</script>
</body>
2子组件访问根组件,$root使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title-hellovuejs</title>
</head>
<body>
<!-- 父组件模板 -->
<div id ="app">
<cpn></cpn>
</div>
<!-- 子组件模板 -->
<template id="cpn1">
<div>
<h2>我是cpn组件</h2>
<ccpn></ccpn>
</div>
</template>
<template id="ccpn">
<div>
<h2>我是子组件</h2>
<button @click="btnClick">按钮</button>
</div>
</template>
<script src="../js/vue.js"></script>
<script>
//1、2父组件中直接创建子组件--root组件
const chen1 = new Vue({
el: '#app', //用于挂载要管理的元素
data:{//定义数据
message: '你好啊'
},
components:{
cpn:{
template: '#cpn1',
data(){
return{
name: '我是cpn组件的name'
}
},
components:{
ccpn:{
template: '#ccpn',
methods:{
btnClick(){
// //1.访问父组件$parent
// console.log(this.$parent);
// console.log(this.$parent.name);
//访问根组件$root
console.log(this.$root);
console.log(this.$root.message);
}
}
}
}
}
}
})
</script>
</body>