Vue组件化

组件化

组件系统是 Vue 的另一个重要概念,因为它是一种抽象,允许我们使用小型、独立和通常可复用的组件构建大型应用。仔细想想,几乎任意类型的应用界面都可以抽象为一个组件树:


image.png

如下,在 Vue 中注册组件,并使用:

// html
<div id="app-7">
  <ol>
    <todo-item
      v-for="item in groceryList"
      v-bind:todo="item"
      v-bind:key="item.id"
    ></todo-item>
  </ol>
</div>
// js
Vue.component('todo-item', {
  props: ['todo'],
  template: '<li>{{ todo.text }}</li>'
})

var app7 = new Vue({
  el: '#app-7',
  data: {
    groceryList: [
      { id: 0, text: '蔬菜' },
      { id: 1, text: '奶酪' },
      { id: 2, text: '随便其它什么人吃的东西' }
    ]
  }
})

组件传值

父组件=>子组件

1.props属性:

// child
props:{msg:String}
// parent
<Son  msg='hello,son'>

2.$attrs特性

// child props不接受的属性都会放在$attrs中
{{$attrs.msg}}
// parent
<Son  msg='hello,son'>

3.refs 场景:用于打开一个子组件弹窗并传值

<Son  ref='sonRef'>
mounted(){
  this.$refs.sonRef.msg="hello,son"
}

4.$children 子组件数组

// parent
mounted(){
  this.$children[0].msg="hello,son"
}

子组件=>父组件

子组件派发自定义事件$emit(),子组件监听到事件时,在父组件中可以拿到参数值

// child
this.$emit('add',msg);
// parent
<Son @add="handleAdd"/>

兄弟组件

$parent--通过父组件派发自定义事件,父组件接收

// brother1
this.$parent.$emit('sayHi','hi');
// brother2
this.$parent.$on('sayHi',handle)

祖先=>后代

props层层传递不优雅,可以使用这对API:provide/inject

// ancestor
provide(){
  return {foo:"777"}
}
// descendent
inject:['foo']

任意两个组件 :

1.事件总线

// main.js
Vue.prototype.$bus=new Vue();
// child1
this.$bus.$on('foo',handle);
// child2
this.$bus.$emit('foo',msg);

2.vuex--终极解决方案

slot插槽及作用域插槽

可以有一部分内容放在父组件文件中写,然后由子组件组织并展示,这就用到slot插槽。

// App.vue 组件中间写内容
<HelloWorld>
      <template>slot</template>
      <template v-slot:content>content</template>
      // content对应的内容会填入到对应作用域下
</HelloWorld>
// HelloWorld.vue 组件内部slot站位
<div class="hello">
    <slot></slot>
    作用域插槽:<slot name="content"></slot>
</div>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 组件化 组件化是vue的核心思想,主要是为了代码重用。 组件通信 父组件=>子组件 属性props 引用refs ...
    benpao2017阅读 1,582评论 0 2
  • 认识组件 组件化开发: ​ 将一个完成的页面,划分成一个个的组件,最终由一个个组件来完成整个页面你的开发,这个...
    cj_jax阅读 192评论 0 1
  • 使用 vue-cli 创建模板项目 vue-cli 是 vue 官方提供的脚手架工具 github: https:...
    leofight阅读 263评论 0 1
  • 使用 vue-cli 创建模板项目 1、说明 1)vue-cli 是 vue 官方提供的脚手架工具2)github...
    qianxun0921阅读 710评论 0 0
  • Vue 组件官网:https://cn.vuejs.org/v2/guide/components.html 组件...
    璎珞纨澜阅读 464评论 0 1