[vue] 怎么访问到子组件的实例或者子元素?
通过
this.$refs
vm.$children
this.$children/this.$refs.xxx
在子组件标签上加 ref属性如ref="baseAlert",在父组件通过this.$refs.baseAlert.子组件方法名。
写了完整的demo,你可看下
<div id="app">
<base-input ref="usernameInput"></base-input>
</div>
<script>
Vue.component("base-input", {
template: "<input type='input' ref='input'>",
methods: {
popUp() {
alert(11)
},
focus: function () {
this.$refs.input.focus()
}
}
});
new Vue({
el: "#app",
data: {},
mounted: function () {
this.$refs.usernameInput.popUp();
this.$refs.usernameInput.focus();
}
});
</script>
Most helpful comment
this.$children/this.$refs.xxx