<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<CNP ref="aaa"></CNP>
<button @click="getchilddata">获取子组件的值</button>
</div>
<template id="cnp">
<div>
{{message}}
<button>我是子组件按钮</button>
</div>
</template>
<script src="../node_modules/vue/dist/vue.js"></script>
<script>
// 通过ref来获取子组件信息
const cnp = {
template:"#cnp",
data(){
return {
message:"WOSHIYIGEZIZUJIAN",
}
}
}
const app = new Vue({
el:"#app",
data:{
arr:[1,2,3,4,5,8],
},
components:{
cnp,
},
methods:{
getchilddata(){
console.log(this.$refs.aaa.message)
}
}
})
</script>
</body>
</html>
只需要在子组件展示的地方添加上ref属性就可以,比如ref=“aaa”,那么父组件要使用子组件的值就可以通过this.$refs.aaa点来获取子组件中属性值。
总结:父组件访问子组件:this.$children,这个可以访问到所有的子组件。this.$refs可以在子组件上面加表示ref="aaa"来具体识别访问子组件。
子组件访问父组件:this.$parent,访问到的是他的直接子组件。
子孙组件可以访问根组件:this.$root,