vue.js 子組件間溝通(透過額外vue instance)

version1(emit+on)

by cactus77kiki

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<div id="uapp">  
  <h3>component communications(version 1)</h3>
  依據(ele-select-a)選取的資料更新(ele-select-b)資料內容
  <ele-select-a v-bind:selected="selectyear" ></ele-select-a>
  <br/>
  <ele-select-b v-bind:selected="selectsub" ></ele-select-b>
</div>

JavaScript

/*
範例:利用emit+on將組件內資料傳出來(可利用於子組件內之溝通)
1. $on=>broadcast、在大型案子內不建議使用
2. 此為version1。version2(較精簡)請見: https://jsfiddle.net/cactus77kiki/ys7d0pc1/
*/
/*
ref1: https://medium.com/%E4%B8%80%E5%80%8B%E5%B0%8F%E5%B0%8F%E5%B7%A5%E7%A8%8B%E5%B8%AB%E7%9A%84%E9%9A%A8%E6%89%8B%E7%AD%86%E8%A8%98/vue-components-%E7%B5%84%E4%BB%B6%E4%B9%8B%E9%96%93%E7%9A%84%E6%BA%9D%E9%80%9A%E6%96%B9%E5%BC%8F-92c1c23c3cc2
ref2: https://stackoverflow.com/questions/45166061/vue-js-firing-emit-not-received-by-on
*/
//中間者(for子組件間傳遞而定義)
var appObj = new Vue({
	data:{
  	select_cyear: ""	
  }
});	
//組件a
Vue.component('ele-select-a',{
	template:`<div>
  						選取年度:{{selection}}<br/>
  						<select v-model="selection" v-on:change="emitdata">
  							<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"}
      ];
    },    
    emitdata: function(){
    	appObj.$emit('select-a-data', this.selection);      
    }    
  },
  created:function(){
  	this.initial();
  }
});
Vue.component('ele-select-b',{
	template:`<div>
  						資料年度:{{selectyear}}<br/>
  						<select v-model="selection">  		
              <option value="">請選擇</option>
  						<option v-for="(row,index) in displaylist" v-bind:value="row.seq">{{row.text}}</option>   
  					</select></div>`,
  props: ["selected"],
  data: function () {
  	return {    	
    	selection: this.selected,         
      datalist:[],
      displaylist:[]
    }
  },  
  computed:{
  	selectyear: function(){	//此組件初始值設定
    	return appObj.select_cyear;    	
    }
  },
  watch:{
  	//當組件(ele-select-a)值異動、傳值出來後異動此組件綁定的資料內容
  	selectyear: function (value) {       	                      ...