子访问父-parent-root
这个用的很少,开发中一般不建议使用
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<cpn></cpn>
</div>
<template id="cpn">
<div>
<ccpn></ccpn>
</div>
</template>
<template id="ccpn">
<div>
<h2>我是子组件</h2>
<button @click="btnClick">按钮</button>
</div>
</template>
<script src="../../vue.min.js"></script>
<script>
const app=new Vue({
el:'#app',
data:{
message:'hello',
},
components:{
cpn:{
template:'#cpn',
data(){
return{
name:'我是cpn组件的name'
}
},
components: {
ccpn:{
template:'#ccpn',
methods:{
btnClick() {
//1.访问父组件
console.log(this.$parent)
console.log(this.$parent.name)
//2.访问根组件
console.log(this.$root)
console.log(this.$root.message)
}
}
}
}
},
}
})
</script>
</body>
</html>