1. 程式人生 > >Vue子元件操作父元件的資料

Vue子元件操作父元件的資料

父元件:

import child from './components/child.vue';

...components:{
    child
},
methods:{
    countChange(opt){
        opt //為子元件傳遞過來的資料,可以是物件
    }
}


<child :c="count" @child-change="countChange"></child>

//@child-change="countChange"中
countChange是父元件的方法,子元件$emit child-change 會觸發父元件的這個方法

子元件:

<template>
	<view>
		<view>{{ c }}</view>
		<view @click="changeCount('up')">&#xe600;</view>
        這裡呼叫的是子元件自己的方法,在此方法中向父元件傳遞資料並執行訂閱事件
	</view>
</template>

<script>
export default {
	data() {
		return {};
	},
	methods: {
		changeCount(type) {
			this.$emit('child-change', { id: this.id, type: type });
		}
	},
	props: {
		c: {
			type: Number,
			default: 1
		}
	}
};
</script>