組件路徑:/views/home/components/bottom.vue 示例:
<template> <div> <h1>底部信息</h1> <div>{{ copyright }} <button v-on:click="setTime">更新時間</button></div> </div> </template> <script> export default { name: "bottom", props: ["copyright"], data() { return {}; }, methods: { setTime() { this.$emit('TimeNow',{'name':'china'}); }, }, }; </script>
組件建立在components文件夾下,傳值使用props,參數是數組形式,this.$emit是觸發父組件的TimeNow事件,以此來調用父組件函數getTimeNow。
使用組件示例:
<template> <div> <h1>首頁</h1> <div>時間:{{tz}}-{{ dt }}</div> <bottom copyright="xxxxx 2020" v-on:TimeNow="getTimeNow"></bottom> </div> </template> <script> import bottom from "@/views/home/components/bottom"; export default { name: "home", components: { bottom }, data() { return { dt: null,tz:'' }; }, methods: { getTimeNow(timeZone) { this.dt = new Date();this.tz=timeZone.name; }, }, }; </script>