学习笔记《Vue components》

组件(components)是 Vue 的一种代码复用机制,components 把 JS 和 HTML 混合到一起,作为整个 Vue 应用层的基础

这篇笔记的内容仅涉及 Components,并不会涉及 Single File Components 这种 Vue SPA 开发中的单文件组件,后者另做介绍

父组件和子组件

从 HTML 结构上来看,「父组件」是指页面载入时候的 HTML模板 中的内容,「父组件」会等待 「子组件」对其进行相关的处理,「父组件」形如:

<div id="componentId">
  <component-tag></component-tag>
</div>

「父组件」首先要进行实例化,才能和「子组件」进行交互,「父组件」的实例化过程形如:

new Vue({
  el: '#componentId',
  data: {
    total: 0
  },
  methods: {
    incrementTotal: function () {
      this.total += 1
    }
  }
})

「子组件」在 HTML 上对「父组件」的指定标签(比如前面的 <component-tag> 标签)进行替换,从而可以与「父组件」进行交互,「子组件」的实例形如:

Vue.component('component-tag', {
  template: '<button v-on:click="methodName">{{ counter }}</button>',
  data: function () {
    return {
      counter: 0
    }
  },
  methods: {
    methodName: function () {
      this.counter += 1
      this.$emit('increment')
    }
  },
})

如果你仅仅希望「子组件」被所在的「父组件」使用,那么也可以直接将「子组件」写到父组件的实例过程中,这样的「父子组件」形如:

new Vue({
  el: '#componentId',
  data: {
    total: 0
  },
  methods: {
    incrementTotal: function () {
      this.total += 1
    }
  },
  components: {
    // <my-component> will only be available in parent's template
    'my-component': {
      template: '<div>A custom component!</div>'
    }
  }
})

「父组件」和「子组件」的交互过程,是通过「父组件」的 props 属性,子组件的自定义事件来完成的,这块的官方文档比较清晰:

In Vue.js, the parent-child component relationship can be summarized as props down, events up. The parent passes data down to the child via props, and the child sends messages to the parent via events. Let’s see how they work next.

父组件和子组件的关系

三种子组件的模板类型

字符串模板(string template):

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

直接将子组件模板定义在「子组件标签」中的 Inline Templates:

<my-component inline-template>
  <div>
    <p>These are compiled as the component's own template.</p>
    <p>Not parent's transclusion content.</p>
  </div>
</my-component>

定义在 <script> 标签中的 X-Templates:

<script type="text/x-template" id="hello-world-template">
  <p>Hello hello hello</p>
</script>

Vue.component('hello-world', {
  template: '#hello-world-template'
})

全局访问子组件

在 Chrome 的 Console 里面调试的时候,直接能够访问到子组件是有一定需求的,这里可以用 ref 属性来实现:

<div id="parent">
  <user-profile ref="profile"></user-profile>
</div>

正常实例化以后就可以这样访问:

var parent = new Vue({ el: '#parent' })
// access child component instance
var child = parent.$refs.profile

Slot

还没有实际遇到,等后面补充

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 下载安装搭建环境 可以选npm安装,或者简单下载一个开发版的vue.js文件 浏览器打开加载有vue的文档时,控制...
    冥冥2017阅读 6,087评论 0 42
  • 这篇笔记主要包含 Vue 2 不同于 Vue 1 或者特有的内容,还有我对于 Vue 1.0 印象不深的内容。关于...
    云之外阅读 5,079评论 0 29
  • Vue 实例 属性和方法 每个 Vue 实例都会代理其 data 对象里所有的属性:var data = { a:...
    云之外阅读 2,241评论 0 6
  • 1.安装 可以简单地在页面引入Vue.js作为独立版本,Vue即被注册为全局变量,可以在页面使用了。 如果希望搭建...
    Awey阅读 11,097评论 4 129
  • 初来乍到,甚是惊喜,交个朋友,喝杯白酒! 作为一只刚踏上运营道路的小透明,任重而道远。 此处不知道该再说什么,所以...
    暂时没有名字吧阅读 236评论 0 0