Vue.js動態載入組件

by cactus77kiki

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>

<div id="dapp">
<h2>
依據選取年度顯示對應下拉選單<br/>
(Vue.js動態載入組件)
</h2>
  <ele-select-a v-bind:selected="selectyear" v-on:changedata="getyear"></ele-select-a>
  <br/>
  <!--若無需keep選取到的值、無須keep-alive標籤-->
  <keep-alive>
  <component v-bind:selected="selectcode" v-bind:is="compname" v-on:changechild="getzone"></component>  
  </keep-alive> 
</div>

JavaScript

//ref: https://cythilya.github.io/2017/10/22/vue-component-dynamic-components/
//第一層下拉選單
Vue.component('ele-select-a',{
	template:`<div>
  						<select 
  						v-model="selection" 
              v-on:change="$emit('changedata',$event,$event.target.selectedIndex)">
  							<option value="">請選擇</option>
  							<option v-for="(row,index) in datalist" v-bind:value="row.code">{{row.text}}</option>              
  					</select></div>`,
  props: ['selected'],
  data: function () {
  	return {
    	selection: this.selected,
      datalist:[]
    }
  },
  methods:{
  	initial: function(){    
    	this.datalist = [      	
        {"code":"98","text":"98"},
        {"code":"102","text":"102"}
      ];
    },
  },
  created:function(){
  	this.initial();
  }
});
//動態組件1
Vue.component('ele-select-b',{
	template:`<select
  						v-model="selection"
  						v-on:change="$emit('changechild',$event,$event.target.selectedIndex)">
  						<option value="">請選擇</option>
  						<option v-for="(row,index) in datalist" v-bind:value="row.code">{{row.text}}</option>              
  					</select>`,
  props: [
  	'selected'
  ],
  data: function () {
  	return {    	
    	selection: this.selected,
      datalist:[]      
    }
  },
  methods:{
  	initial: function(){    
    	this.datalist = [
      	{"year":"98","code":"a","text":"台北市"},
        {"year":"98","code":"b","text":"台北縣"},
        {"year":"98","code":"c","text":"基隆市"}             
      ];      
    }
  },
  created:function(){
  	this.initial();
  }
});
//動態組件2
Vue.component('ele-select-c',{
	template:`<select 
  						v-model="selection"
  						v-on:change="$emit('changechild',$event,$event.target.selectedIndex)">
  						<option value="">請選擇</option>
  						<option v-for="(row,index) in datalist" v-bind:value="row.code">{{row.text}}</option>              
  					</select>`,
  props: [
  	'selected'
  ],
  data: function () {
  	return {
    	selection: this.selected,
      datalist:[]      
    }
  },
  methods:{
 ...