Vue3(6)组件化开发的基本概念

如何定义一个组件

引入一个component

  <div id="app">
    <hello></hello>
  </div>
  <script src="https://unpkg.com/vue@next"></script>
  <script>
    const app = Vue.createApp({
      data(){
        return {
        
        }
      }
    })

    app.component("hello",{
      template: `
        <h1>hello component</h1>
      `
    })

    app.mount("#app")
  </script>

这样就实现了一个hello的组件

组件的复用

  <div id="app">
    <my-fruit-list></my-fruit-list>
    <my-fruit-list></my-fruit-list>
    <my-fruit-list></my-fruit-list>
  </div>
  <script src="https://unpkg.com/vue@next"></script>
  <script>
    const app = Vue.createApp({});
    app.component("my-fruit-list",{
      template:`
        <div>水果</div>
        <my-counter></my-counter>
      `
    });
    app.component("my-counter",{
      data(){
        return {
          msg:0
        }
      },
      methods: {
        increase(){
          this.msg++
        },
        decrease(){
          if(this.msg>0){
            this.msg--
          }
        }
      },
      template:`
        <button @click="decrease">-</button>
        <span>{{msg}}</span>
        <button @click="increase">+</button>
      `
    })
    app.mount("#app")
  </script>

这样既通过自定义组件实现了复用,并且组件之间也互不影响

posted @ 2021-08-01 12:05  `Duet`  阅读(107)  评论(0编辑  收藏  举报