1. 程式人生 > 實用技巧 >Vue基礎(三)---- 元件化開發

Vue基礎(三)---- 元件化開發

基本結構: ◆1、元件化開發思想 ◆2、元件註冊 ◆3、Vue除錯工具用法 ◆4、元件間資料互動 ◆5、元件插槽 ◆6、基於元件的案例 ◆1、元件化開發思想   優點:     提高開發效率
    方便重複使用
    簡化除錯步驟
    提升整個專案的可維護性
    便於多人協同開發 ◆2、元件註冊   2.1 全域性元件
    1> 全域性元件註冊語法               2> 元件用法         3> 元件註冊注意事項         1、元件引數的data值必須是函式    2、元件模板必須是單個根元素    3、元件模板的內容可以是模板字串(``,因為放在一行內可能造成程式碼可讀性差)

      4. 元件命名方式:           短橫線方式 Vue.component('my-component', { /* ... */ })           駝峰方式 Vue.component('MyComponent', { /* ... */ })     4> 具體使用  
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <button-counter></button-counter>
      <button-counter></button-counter>
      <button-counter></button-counter>
</div> <script type="text/javascript" src="js/vue.js"></script> <script type="text/javascript"> /* 元件註冊注意事項 1、元件引數的data值必須是函式 2、元件模板必須是單個根元素 3、元件模板的內容可以是模板字串( ``,因為放在一行內可能造成程式碼可讀性差) */ Vue.component("button-counter", { data:
function () { return { count: 0, }; }, // template: '<div><button @click="handle">點選了{{count}}次</button><button>測試</button></div>', template: ` <div> <button @click="handle">點選了{{count}}次</button> <button>測試123</button> </div> `, methods: { handle: function () { this.count += 2; }, }, }); var vm = new Vue({ el: "#app", data: { }, }); </script> </body> </html>

  2.2 區域性元件
    1> 區域性元件註冊語法             2> 注意事項及程式碼     
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <hello-world></hello-world>
    <hello-tom></hello-tom>
    <hello-jerry></hello-jerry>
    <test-com></test-com>
  </div>
  <script type="text/javascript" src="js/vue.js"></script>
  <script type="text/javascript">
    /*
      區域性元件註冊
        區域性元件只能在註冊他的父元件中使用
    */
    Vue.component('test-com',{    
      template: '<div>Test<hello-world></hello-world></div>',
      //全域性元件中不可用,只能在註冊他的父元件中使用  <div id="app"></div>
    });
    
    var HelloWorld = {
      data: function(){
        return {
          msg: 'HelloWorld'
        }
      },
      template: '<div>{{msg}}</div>'
    };
    
    var HelloTom = {
      data: function(){
        return {
          msg: 'HelloTom'
        }
      },
      template: '<div>{{msg}}</div>'
    };
    
    var HelloJerry = {
      data: function(){
        return {
          msg: 'HelloJerry'
        }
      },
      template: '<div>{{msg}}</div>'
    };
    
    var vm = new Vue({
      el: '#app',
      data: {
        
      },
      components: {
        'hello-world': HelloWorld,
        'hello-tom': HelloTom,
        'hello-jerry': HelloJerry
      }
    });
  </script>
</body>
</html>

     ◆4、元件間資料互動   4.1 父元件向子元件傳值   4.2 子元件向父元件傳值   4.3 兄弟元件間傳值