vue笔记——vue中的子组件引用

来源:互联网 发布:淘宝收费标准 编辑:程序博客网 时间:2024/06/08 19:24

vue官网是这样描述$refs的

在javascript中直接访问子组件,可以使用ref为子组件指定一个引用ID

<div id="parent">  <user-profile ref="profile"></user-profile></div>
var parent = new Vue({ el: '#parent' })// 访问子组件实例var child = parent.$refs.profile

$refs 只在组件渲染完成后才填充,并且它是非响应式的。它仅仅是一个直接操作子组件的应急方案——应当避免在模板或计算属性中使用 $refs


vue官网是这样描述ref的

ref 被用来给元素或子组件注册引用信息。引用信息将会注册在父组件的 $refs 对象上。如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子组件上,引用就指向组件实例:

<!-- vm.$refs.p will be the DOM node --><p ref="p">hello</p>
<!-- vm.$refs.child will be the child comp instance --><child-comp ref="child"></child-comp>
当 v-for 用于元素或组件的时候,引用信息将是包含 DOM 节点或组件实例的数组。

关于 ref 注册时间的重要说明:因为 ref 本身是作为渲染结果被创建的,在初始渲染的时候你不能访问它们 - 它们还不存在!$refs 也不是响应式的,因此你不应该试图用它在模板中做数据绑定。


一个例子是这样的:

child1.vue

<template>    <div>        child1    </div></template><script>    export default {        name: "child1",        props: "msg",        methods: {            handleParentClick(e) {                console.info(e)            }        }    }</script>
parent.vue

<template>    <div>        <button v-on:click="clickParent">点击</button>        <child1 ref="child1"></child1>    </div></template><script>    import Child1 from './child1';    export default {        name: "parent",        components: {            child1: Child1        },        methods: {            clickParent() {                // this.$refs.child1.$emit('click-child', "high");                this.$refs.child1.handleParentClick("ssss");            }        }    }</script>
this.$refs.child1.handleParentClick("ssss")获取父组件中HTML中的<child1 ref="child1"></child1>实例,并调用子组件的methods中的

函数.handleParentClick("ssss"),参数为“ssss”。


原创粉丝点击