
組件 (Component) 是 Vue.js 最強大的功能之一。
可用於組件封裝來優化程序
子組件代碼
<template>
<div>
child
</div>
</template>
<script>
export default {
name: "child",
props: "someprops",
methods: {
parentHandleclick(e) {
console.log(e)
}
}
}
</script>
父組件代碼
<template>
<div>
<button @click="clickParent">點擊</button>
<child ref="mychild"></child>
</div>
</template>
<script>
import Child from './child';
export default {
name: "parent",
components: {
child: Child
},
methods: {
clickParent() {
this.$refs.mychild.parentHandleclick("嘿嘿嘿");
}
}
}
</script>
ps:
1、在子組件中:<div></div>是必須要存在的
2、在父組件中:首先要引入子組件 import Child from './child';
3、 <child ref="mychild"></child>是在父組件中為子組件添加一個占位,ref="mychild"是子組件在父組件中的名字
4、父組件中 components: { 是聲明子組件在父組件中的名字
5、在父組件的方法中調用子組件的方法,很重要 this.$refs.mychild.parentHandleclick("嘿嘿嘿");
