美文网首页
Vue父组件获取子组件中的变量

Vue父组件获取子组件中的变量

作者: 坏丶毛病 | 来源:发表于2020-03-01 22:07 被阅读0次

    在vue项目日常开发中,难免要把功能性组件抽离出来,这样结构就会出现父子组价,兄弟组件等,但是这样就会涉及到不同组件需要互相使用其中的值得问题。

    之前有说过通过ref来让父组件操作子组件,并且传值,那么我们今天来详细看看。

    案例一:点击父组件的按钮,操作子组件显示

    注:可以通过获取id/class来操作,这里我就不介绍这种方法了,至于jquery的话,在vue中还是慎用。

    介绍:这里通过给子组件绑定ref属性,引号命名自定义,然后父组件通过 this.$refs.名字 就可以操作子组件的元素,以改变它的样式等。

    <template>
        <div class="DbSource-box">
            <el-button type="primary" icon="" class="addBtn" @click="addDbSource()">新增</el-button>
            <db-source-add ref="addAlert" v-on:init="init"></db-source-add>
        </div>
    </template>
    
    <script>
        import DbSourceAdd from "../components/DbSourceManager/DbSourceAdd";
        export default {
            name: "DbSourceManager",
            components: {DbSourceAdd},
            methods: {
                // 点击新增按钮,弹出新增数据源的弹框
                addDbSource(){
                    this.$refs.addAlert.$el.style.display = "block";
                },
            }
        }
    </script>
    

    案列二:获取子组件data中的变量

    介绍:

    父组件:

    这里通过给子组件绑定ref属性,引号中的命名自定义,然后父组件通过 this.$refs.名字.变量名 就可以获得子组件中的值

    <template>
        <div class="DbSource-box">
            <el-button type="primary" icon="" class="selectBtn" @click="deleteSelectDbSource()">批量删除</el-button>
            <db-source-table ref="getSelectData" :Data="Data" v-on:init="init"></db-source-table>
        </div>
    </template>
    
    <script>
        import DbSourceTable from "../components/DbSourceManager/DbSourceTable";
        export default {
            name: "DbSourceManager",
            components: {DbSourceTable},
            methods: {
                // 删除选中的数据源(批量删除)
                deleteSelectDbSource(){
                    console.log(this.$refs.getSelectData.multipleSelection)
                },
            }
        }
    </script>
    

    子组件:

    <template>
        <div class="table-box">
    
        </div>
    </template>
    
    <script>
        export default {
            name: "DbSourceTable",
            props:["Data"],
            data(){
                return {
                    multipleSelection:[],
                    pagesize: 3,
                    currpage: 1,
                    currId:""
                }
            }
    </script>
    

    好了,以上就是父组件获取子组件的值并且操作子组件的方法。

    image image

    如有问题,请指出,接受批评。

    相关文章

      网友评论

          本文标题:Vue父组件获取子组件中的变量

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