vue.js 子組件間溝通(透過額外vue instance)
version2(function建立於額外vue instance內)
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(version2)</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. 此為version2(直接改變new instance值)。version1請見: https://jsfiddle.net/cactus77kiki/ganjzwyf/
*/
/*
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: ""
},
methods:{
transfering: function(param){
this.select_cyear = param;
}
}
});
//組件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.transfering(this.selection);
}
},
created:function(){
this.initial();
}
});
//組件b
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:{
...