vue的ref

作者: 蠢淡淡不蠢 | 来源:发表于2018-06-25 22:47 被阅读0次

$refs

尽管有props和events,但是仍然需要在JavaScript中直接访问子组件。

为此可以使用ref为子组件指定一个索引ID。

注意,ref并不是动态更新的,也就是说不应该绑定变量,而是写一个固定值即可。

home.vue中添加list组件

<div class="home">
    <list ref="childList"></list>
    <button @click="getChild()">获取子组件</button>
</div>

home.vue中的的方法中,可以直接访问到子组件对象

import List from '../components/list'
export default {
    components: { List },
    methods: {
        getChild() {
            // 获取子组件中的数据
            console.log(this.$refs.childList.$data.name);

            // 调用子组件中的方法
            this.$refs.childList.test1();
        }
    }
}

list.vue组件中的数据:

export default {
    data() {
        return {
            name: 'list',
            version: '1.0.0'
        }
    },
    methods: {
        test1() {
            console.log('test1');
        },
        test2() {
            console.log('test2');
        }
    }
}

子组件向父组件传值

注意:子组件同样也可以调用父组件中的方法,通过props传值即可

通过此种方法,子组件也可以传值给父组件

父组件中

<template lang="html">
    <div class="home">
        <list :func="test3"></list>
    </div>
</template>

<script>
import List from '../components/list'
export default {
    components: { List },
    methods: {
        test3(value) { // 参数value就是子组件传递给父组件的值
            console.log('test3', value);
        }
    }
}
</script>

<style lang="css">
</style>

子组件中

<template lang="html">
    <div class="list">
        <ul>
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
        </ul>
        <button @click="userParentFunc()">调用父组件中的方法</button>
    </div>
</template>

<script>
export default {
    props: ['func'],
    methods: {
        userParentFunc() {
            this.func('我是子组件中的数据');
        }
    }
}
</script>

<style lang="css" scoped>
</style>

相关文章

  • vue - ref

    vue - ref 说明 ref 是英文单词 reference,代表引用. 在 vue 中, ref 的使用分四...

  • 13-Vue特殊属性-ref

    一、Vue特殊特性 Vue的特殊属性主要有:key、ref、is、slot,ref是Vue特殊属性之一 ref:被...

  • Vue3 Ref 与 Reactive的区别

    Vue3 在组件中使用ref()或reactive()都可以创建响应式数据 Vue2 中操作 Vue3 ref r...

  • 初探Vue的ref($ref)

    1、ref官方文档API2、我的理解就是ref定义在父组件中,且他有一个名称 这样在父组件的实例里就存在一个变量v...

  • 初探Vue的ref($ref)

    1、ref官方文档API[https://cn.vuejs.org/v2/api/#ref]2、我的理解就是ref...

  • vue3中警告app.config.unwrapInjected

    [Vue warn]: injected property "formItemEmitter" is a ref ...

  • Vue 及双向数据绑定 Vue事件介绍 以及Vue中的ref获取

    1,vue的双向数据绑定和Vue事件介绍 2,Vue中ref获取dom节点

  • vue -- ref

    访问子组件实例或子元素 尽管存在 prop 和事件,有的时候你仍可能需要在 JavaScript 里直接访问一个子...

  • vue的ref

    $refs 尽管有props和events,但是仍然需要在JavaScript中直接访问子组件。 为此可以使用re...

  • vue3学习

    一、基础语法 1、双向数据绑定 vue2 vue3 2、ref, reactive ref:一般用在定义基本类型和...

网友评论

      本文标题:vue的ref

      本文链接:https://www.haomeiwen.com/subject/kkvuyftx.html