Vue里$refs用法
- 用法一:ref加在普通的元素上,用this.$refs.name获取到的是dom元素
- 用法二:ref加在组件上,用this.$refs.name获取到的是组件实例,可以使用组价的所有方法
$parent用法
- 通过this.$parent可以访问到当前组件的父组件里所有的数据以及方法
Vue组件通信练习巩固
题目:
在Vue实例下data数据层有一个数组list(数据任意存放),2个组件,组件1 cpn1有子组件cpnn1,cpnn1有子组件cpnnn1,
在组件cpnnn1中有一个空数组sonList,一个getList方法(该方法要求在父组件中获取list数组且赋值给sonList)
需求:在组件2 cpn2中获取cpnnn1中的方法然后获取到sonList数组的值,在cpn2中以列表形式展示
分析: 题目大概意思如下图
程序:
<!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>父子通信</title>
<script src="../../js/vue.js"></script>
</head>
<body>
<div id="app" style="border: 5px solid rgb(228, 119, 119);">
<div>
<h1>父</h1>
<cpn1 ref="c1"></cpn1>
<cpn2 ></cpn2>
<h3>{{list}}</h3>
</div>
</div>
<template lang="" id="cpn1">
<div style="border: 5px solid blueviolet;">
<h2>cpn1</h2>
<Cpn2 ref="c2"></Cpn2>
</div>
</template>
<template lang="" id="cpn2">
<div style="border: 5px solid rgb(10, 224, 156);">
<h2>cpn2</h2>
<button @click="get_cpnnn1_list">获取cpnnn1的数据并展示</button>
<ol>
<li v-for="obj in myList" :key="obj.id">
{{obj.name}}
</li>
</ol>
</div>
</template>
<template lang="" id="cpnn1">
<div style="border: 5px solid rgb(231, 165, 22);">
<h2>cpnn1</h2>
<Cpn3 ref='c3'></Cpn3>
</div>
</template>
<template lang="" id="cpnnn1">
<div style="border: 5px solid rgb(248, 13, 13);">
<h2>cpnnn1</h2>
<button @click="getList">从父组件获取数组数据</button>
</div>
</template>
<script>
new Vue({
el:'#app',
data() {
return {
list:[
{
id:1,
name:'小红'
},
{
id:2,
name:'小白'
},
{
id:3,
name:'小蓝'
}
]
}
},
components:{
cpn1:{
template:'#cpn1',
components:{
Cpn2:{
template:'#cpnn1',
components:{
Cpn3:{
template:'#cpnnn1',
data() {
return {
sonList:[{}]
}
},
methods: {
getList(){
console.log(this.$parent.$parent.$parent.list)
this.sonList=this.$parent.$parent.$parent.list
console.log(this.sonList)
console.log(this.sonList[0].name)
}
},
}
}
}
}
},
cpn2:{
template:'#cpn2',
data() {
return {
myList:[]
}
},
methods:{
get_cpnnn1_list(){
this.myList=this.$parent.$refs.c1.$refs.c2.$refs.c3.sonList
}
}
}
}
})
</script>
</body>
</html>
运行效果:
先点击上面的"从父组件获取数组数据"按钮,在点击“获取cpnnn1的数据并显示”这个按钮
最终效果如下: