當你開始使用 Vue.js  的 components(組件) 時,會經常使用到父子組件,需要互相執行方法(mothods)的問題!

今天來說說,如何由子組件按鈕(v-on:click)時,如何去執行父組件裡的方法。

大致的狀況說明,當您的是個CRUD網頁,想把常用工具欄位,獨立為一個Vue檔(在這為Child.vue),以便日後共用及修改方便使用

結果當獨立出來後,發現 Child 子組件的 update ,還是須要到父組件完成,因為有可能表單資料都在父組件,你在子組件點 update

變成沒有用,就必須在子組件去 觸動父組件的方法(mothods),以完成update的工作

parents.vue

undefined

 

<template lang="pug">
    div
        app-child(
            v-on:update-item="updateItem(model,vuex)"
        )
</template>
<!-- script -->
<script type="es6">
    import Child from './Child.vue'

    export default{
        components: {
            appChild: Child,
        },
        data(){
            return {}
        },
        methods:    {
            updateItme(model,vuex){
                // do Something
            }
        }
    }
</script>

Child.vue

 

undefined

 
<template lang="pug">
    div
        a(
            v-on:click="updateClick()"
        ) update
</template>
<!-- script -->
<script type="es6">
    export default{
        data(){
            return {

            }
        },
        components: {},
        methods:    {
            updateClick(){
                this.$emit('update-item')
            }
        }
    }
</script>

上圖,可由 父組件 Parent 利用 v-on:update-item="updateItem()"

子組件 Child 利用 在方法裡,利用 this.$emit('update-itme')

就以完成執行!!

 

可以試試喔!

 

 

arrow
arrow
    文章標籤
    vue javascript web
    全站熱搜

    雲橙雨林 發表在 痞客邦 留言(0) 人氣()