<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue父访问子</title>
</head>
<body>
<div class="app" id="app">
<h2>vue父访问子两种方式</h2>
<ul>
<li>this.$children,通过下标访问,不常用</li>
<li>this.$refs,通过指定名字访问,常用</li>
</ul>
<cpn></cpn>
<cpn></cpn>
<cpn ref='refname'></cpn>
<button @click='way_child'>children访问</button>
<button @click='way_refs'>refs访问</button>
</div>
<template id="cpn">
<div>
我是子组件内容
</div>
</template>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12"></script>
<script>
const cpn = {
template:'#cpn',
data(){
return {
name:'我是name'
}
},
methods:{
item_click(){
console.log('item_clicked')
},
},
}
const app = new Vue({
el:'#app',
data:{},
components:{'cpn':cpn},
methods:{
way_child(){
console.log('children查看所有组件',this.$children)
console.log('children访问下标0的name',this.$children[0].name)
},
way_refs(){
console.log('refs定向访问',this.$refs.refname.name)
}
}
})
</script>
</body>
</html>
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/256a657c2f12e52675b0ebce6b126cde.png)
- 子访问父通过:
- 1、this.$parent 访问上一级组件,也可能是vue实例
- 2、this.$root 访问根组件,即系vue实例