try: vue 3.x - dynamic component

practice code when study

by cactus77kiki

HTML

<script src="https://unpkg.com/[email protected]"></script>

<div id="appbox">
    <!--test-->
    <span>{{msg}}</span><br/>
        
    稅前金額:<input type="text" v-model="amtexcludingtax"/><br/>
    計算方式:
    <select v-model="selectmode">
      <option value="">- 請選擇 -</option>
      <option value="comp-test">1</option>
      <option value="comp-test3">3</option>
    </select>
    
    <component :is="selectmode" :inputamt="amtexcludingtax" :getdata = "getPriceAfterTax" :rate="rater"></component>
    <!--<comp-test :inputamt="amtexcludingtax" :getdata = "getPriceAfterTax"></comp-test>-->
    <span v-if="selectmode!=''">稅後金額:{{amtincludingtax}}</span>
  </div>

JavaScript

//comp1
    let TestComponent = {
      props: {
        inputamt: {
          type: String,
        },
        rate: {
          type: String,
        },
        getdata: { type:Function },
      },
      data(){
        return { 
          
        }
      },
      methods: {
        calPriceAfterTax(){                
          this.getdata(Number(this.inputamt)*Number(this.rate));          
        }
      },
      template: `<div><button v-on:click="calPriceAfterTax">計算</button></div>`
    };   
    
    const vapp = Vue.createApp({			
      data() {
        return {
          msg: '',
          amtexcludingtax: "0",
          amtincludingtax: "0",
          amtcalculate2:"0",
          selectmode:"",
          rate1: "1.05",
          rate3: "1000",
        }
      },
      computed:{
        rater(){
          let data = "";
          switch(this.selectmode){
            case "comp-test3":
              data = this.rate3;
              break;
            default:
              data = this.rate1;
              break;
          }
          return data;
        }
      },
      methods:{
        initialized(){
          this.msg = 'test';
        },
        getPriceAfterTax(amt){
          this.amtincludingtax = amt;
          //console.log(amt);
        },
        getPriceAfterCalculate(amt){
          this.amtcalculate2 = amt;
          //console.log(amt);
        },
      },
      components: {
      	'comp-test': TestComponent,
        'comp-test3': TestComponent,
      },
      created(){
        this.initialized();
      }
    });
    /*
    vapp
  .component('ComponentA', {
      
      
    });

    
        vapp
  .component('ComponentB', {
      
      
    });
    */
    vapp.mount('#appbox'); 
    
    /*
    ref: https://book.vue.tw/CH2/2-3-async-dynamic-components.html
    */