vue的ref

$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 2 不同于 Vue 1 或者特有的内容,还有我对于 Vue 1.0 印象不深的内容。关于...
    云之外阅读 10,460评论 0 29
  • Vue 实例 属性和方法 每个 Vue 实例都会代理其 data 对象里所有的属性:var data = { a:...
    云之外阅读 6,648评论 0 6
  • 1.安装 可以简单地在页面引入Vue.js作为独立版本,Vue即被注册为全局变量,可以在页面使用了。 如果希望搭建...
    Awey阅读 13,787评论 4 129
  • 今人读古人诗文,常觉他们离愁别绪万种相思真是百转千回丝丝入扣,也不是古人多情,只是山水隔阻,音信难达,一别经年便是...
    籽盐阅读 988评论 0 1
  • pip 安装地址 注意就是 权限问题: 使用sudo 命令 使用python3 以下的版本,添加第三方的时候使用s...
    司马捷阅读 4,822评论 0 1