Vue - 全局组件及父子组件

组件 (Component) 是 Vue.js 最强大的功能之一。组件可以扩展 HTML 元素,封装可重用的代码。在较高层面上,组件是自定义元素,Vue.js 的编译器为它添加特殊功能。在有些情况下,组件也可以表现为用 is 特性进行了扩展的原生 HTML 元素。

所有的 Vue 组件同时也都是 Vue 的实例,所以可接受相同的选项对象 (除了一些根级特有的选项) 并提供相同的生命周期钩子。

注册一个全局组件,可以使用Vue.component(tagName, options)

Vue.component('my-component', {
  // 选项
})

组件在注册之后,便可以作为自定义元素 <my-component></my-component>在一个实例的模板中使用。注意确保在初始化根实例之前注册组件

// 注册
Vue.component('my-component', {
  template: '<div>A custom component!</div>'
})

// 创建根实例
new Vue({
  el: '#example'
})

如此长篇大论copy自Vue API

<div id="app">
  <my-test></my-test>
</div>
<script src="vue.js"></script>
<script>
  // 1.创建组件构造器
  let Profile = Vue.extend({
    // 1.1 模板选项
    template:`
      <div>
        <p>测试</p>
      </div>
      `
  });
  // 2.注册一个全局的组件
  Vue.component('my-test',Profile);

  new Vue({
    el: '#app',
  });
</script>

<div id="app">
  <my-test></my-test>
</div>
<script src="vue.js"></script>
<script>
  Vue.component('my-test',{
    template:`
    <div>
      <p>测试</p>
    </div>
    `
  });
  new Vue({
    el: '#app',
  });
</script>

作用一致

父子组件

<div id="app">
  <parent></parent>
</div>
<script src="js/vue.js"></script>
<script>
  // 1.子组件构造器
  // 若要使用这些组件,需要在外面重新注册
  let Child1 = Vue.extend({
    template: `<img src="img_01.png" width="340">`
  });
  let Child2 = Vue.extend({
    template: `<p>啦啦啦</p>`
  });
  // 2.父组件构造器
  Vue.component('parent',{
    components: {
      'my-child1': Child1,
      'my-child2': Child2
    },
    template:
      `
        <div>
          <my-child1></my-child1>
          <my-child2></my-child2>
        </div>
      `
  });
  new Vue({
    el: '#app'
  });
</script>

挂载选项

data必须是函数

构造 Vue 实例时传入的各种选项大多数都可以在组件里使用。只有一个例外:data 必须是函数

Vue.component('my-component', {
  template: '<span>{{ message }}</span>',
  data: {
    message: 'hello'
  }
})

那么 Vue 会停止运行,并在控制台发出警告,只有data为函数才能用
示例:

<div id="app">
  <my-div></my-div>
</div>
<script id="my-div" type="test/template">
  <div>
    <p>说你是猪!</p>
    <input type="text" placeholder="说你是猪">
    <p>{{msg}}</p>
  </div>
</script>
<script src="js/vue.js"></script>
<script>
  Vue.component('my-div',{
    template: '#my-div',
    data(){
      return {
        msg: '哈哈哈哈!'
      }
    }
  });
  new Vue({
    el: '#app'
  });
</script>

猜你喜欢

转载自blog.csdn.net/qq_38265784/article/details/80006048