zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    python--DAY7面向对象进阶
    python--socket实例
    Python---day5-各类模块的使用
    python--day4--迭代器、生成器
    Python--三元运算与lambda表达式
    python--函数式登录程序
    Python--变量作用域
    Python--函数
    Python----文件的IO操作
    swagger2文档的步骤
  • 原文地址:https://www.cnblogs.com/windok/p/13391537.html
Copyright © 2011-2022 走看看