简单实现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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章