簡單實現vue-cli下的動態組件

前提

這只是開發中簡單實現的,可能會繁瑣,待改進中

數據

data.js

export default {
    "avatar": {
        "headIconURL": "",
        "name":"APAD",
        "description": "",
        "skills": []
    },
    "contact":{
        "phone":9999,
        "email":"[email protected]"
    },
    "education": {
        "school": "家裏蹲大學",
        "specialty": "",
        "education_background": "本科",
        "time_from": 2016,
        "time_to": 2020
    },
    "project": [
        {
            "name": "",
            "haveJobExperience": false,
            "description": "",
            "achievement": "",
            "time_from": "2019-8",
            "time_to": "2019-8",
            "link": ""
        }
    ],
    "socialPage": [
        {"name":"","URL":""}
    ]
}

main.js

import Vue from 'vue'
import store from './store'
Vue.prototype.store = store

new Vue({
  render: h => h(App),
}).$mount('#app')

組件

例出兩個組件

avatar.vue

<template>
  <section>
    <div class="avatar">
      <!-- 頭像 -->
      <img :src="data.avatar.headIconURL || 'https://iconfont.alicdn.com/t/1510710350863.png@100h_100w.jpg'" alt="頭像" />
      <!-- 名字 -->
      <h2>{{data.avatar.name}}</h2>
      <!-- 學校/學歷 -->
      <p>{{data.education.school}} / {{data.education.education_background}}</p>
    </div>
  </section>
</template>

<script>
export default {
  data() {
    return {
      data: this.store.data
    };
  }
};
</script>

<style>
</style>

education.vue

<template>
  <section>
    <div class="education">
      <h2>教育經歷</h2>
      <!-- 學校 -->
      <p>{{data.education.school}}</p>
      <!-- 學歷 | 專業 -->
      <p>{{data.education.education_background}} | {{data.education.specialty}}</p>
      <!-- 時間 -->
      <p>{{data.education.time_from}} - {{data.education.time_to}}</p>
    </div>
  </section>
</template>

<script>
export default {
  data() {
    return {
      data: this.store.data
    };
  }
};
</script>

<style>
</style>

整合

隨便叫什麼的.vue

<template>
  <div>
    <button @click="changeContext">change</button>
    
    <component
      :is="currentTab">
    </component>
  </div>
</template>

<script>
import avatar from './avatar'
import education from './education'

export default {
  data() {
    return {
      currentTab: 'avatar' // 這裏的'avatar'可以是字符串也可以是import的avatar
    };
  },
  methods: {
    changeContext(e) {
    // 用來測試的
      this.currentTab = 'education'
    }
  },
  components:{
    // 這裏導入組件是必要的
    avatar,
    education
  }
};
</script>

<style>
</style>

運行

  • 默認下
    默認
  • 點擊change
    change
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章