1. 程式人生 > >vue元件之間的傳值

vue元件之間的傳值

元件傳參:
元件例項的作用域是孤立的。這意味著不能在子元件的模組中直接引用父元件的資料,必須使用特定的方法才能實現元件之間的資料傳遞。
如在父元件中向子元件傳值

<headerBar message = “hello” />

在子元件中需要使用props獲取到父元件的傳值:

props: [‘message’]

子元件向父元件傳遞資料,如當input發生變化時,向子元件傳name值:

<input v-model = “name” @change = “setName” />
    methods: {
        setName: function
(){
this.$emit(‘transferName’, this.name) } }

在父元件中獲取資料:

<headerBar @transferName = “getName”/>
    methods: {
        getName: function(msg){
            this.user = msg
        }
    }

子子元件傳遞資料
子元件之間不能相互傳值,那麼必須依靠父元件來進行值的傳遞,即子元件的值傳遞到父元件,再由父元件傳遞到另一個子元件。
如我們定義一個data,讓它從子元件向父元件傳遞:

let data = {
    iss: this.iss
    con: this.textContent
    url: this.upImgUrl
}
this.$emit('listen', data)

在父元件中接收資料:(注意標籤issue是寫在父元件中的一個子元件)

<issue v-show="index == 0" v-on:listen="listenMsg"/>

因為子元件中傳送了一個listen事件,則在使用子元件時需要借用這個listen事件:

listenMsg(data){
     this.postData = data;
}

在父元件中定義postData獲取到資料。
從父元件向另一個子元件傳遞值:

<circlepage v-show="index == 1" :data="postData"/>

在circle中獲取值,但是如果直接在mounter中獲取值,則只能獲取到原始值,並不能監測到另一個子元件傳遞過來的值,所以我們需要在watch中來獲取數值:

props: [‘data’],
    watch: {
        data(newVal){
            this.circleList.unshift(newVal);
        }
    }

這樣,我們完成了子元件與父元件,父元件與子元件的傳值。