一.父子组件之间属性访问
通常父子组件是可以进行属性访问的,例如父组件调用子组件中的方法,变量等,这些都是可以通过拿到各自对应的父子组件对象,然后调用其属性,例如:
父组件访问子组件中的属性有两种方式
- 在父组件中使用this.$children拿到所有的子组件数组对象,然后索引访问对应子组件中的方法,变量等属性
- 通过this.$refs(子组件名称来访问),这种相比于第一种就是可以通过子组件的具体名称来访问了,避免索引顺序改变问题
1.1 父组件访问子组件(this.$children,this.$refs)
1.$children获取子组件对象列表
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>父子组件访问</title>
<script src="./vue.js"></script>
<style>
[v-cloak] {
display: none;
}
</style>
</head>
<body>
<div id="app" v-cloak>
<component1></component1>
<button @click="btnclick">按钮</button>
</div>
<template id="content">
<div>
<span>子组件中的内容</span>
</div>
</template>
<script>
const vm = new Vue({
el:"#app",
data:{
},
methods:{
btnclick(){
console.log(this.$children); // this.$children返回的数所有子组件对象的数组
this.$children[0].