一、父组件向子组件通信
方法一:props
使用props,父组件可以使用props向子组件传递数据。
父组件vue模板father.vue
<template>
<child :msg="message"></child>
</template>
<script>
import child from './child.vue';
export default {
components: {
child
},
data () {
return {
message: 'father message';
}
}
}
</script>
子组件vue模板child.vue
<template>
<div>{{msg}}</div>
</template>
<script>
export default {
props: {
msg: {
type: String,
required: true
}
}
}
</script>
方法二 使用$children
使用$children可以在父组件中访问子组件。
当子组件较多时,通过this.$children来一一遍历出我们需要的一个组件实例是比较困难的,vue提供了子组件索引的方法,用特殊的属性ref来为子组件指定一个索引名称
<base-input ref="usernameInput"></base-input>
现在在你已经定义了这个 ref
的组件里,你可以使用:
this.$refs.usernameInput
来访问这个 <base-input>
实例,以便不时之需。比如程序化的从一个父级组件聚焦这个输入框。在刚才那个例子中,该 <base-input>
组件也可以使用一个类似的 ref
提供对内部这个指定元素的访问,例如:
<input ref="input">
甚至可以通过其父级组件定义方法:
methods: {
// 用来从父级组件聚焦输入框
focus: function () {
this.$refs.input.focus()
}
}
这样就允许父级组件通过下面的代码聚焦 <base-input>
里的输入框:
this.$refs.usernameInput.focus()
$refs
只会在组件渲染完成之后生效,并且它们不是响应式的。这只意味着一个直接的子组件封装的“逃生舱”——你应该避免在模板或计算属性中访问 $refs
。