Vue2

Vue2(二):组件

2020-12-06  本文已影响0人  wsgdiv

注册全局组件

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

局部注册

var Child = {
  template: '<div>A custom component!</div>'
}
new Vue({
  // ...
  components: {
    // <my-component> 将只在父模板可用
    'my-component': Child
  }
})

ps:这种封装也适用于其它可注册的 Vue 功能,如指令。
<ul> , <ol>, <table> , <select> 时:用 is 属性。

<table>
  <tr is="my-row"></tr>
</table>

注意:data 必须是函数

组件通信

用 props 把数据传给子组件

Vue.component('child', {
  // 声明 props
  props: ['message'],
  // 就像 data 一样,prop 可以用在模板内
  // 同样也可以在 vm 实例中像 “this.message” 这样使用
  template: '<span>{{ message }}</span>'
})

动态 Props:用 v-bind 动态绑定 props 的值到父组件的数据

<div>
  <input v-model="parentMsg">
  <br>
  <child v-bind:my-message="parentMsg"></child>
</div>

prop 是单向绑定的:当父组件的属性变化时,将传导给子组件,但是不会反过来。

Prop 验证

Vue.component('example', {
  props: {
    // 基础类型检测 (`null` 意思是任何类型都可以)
    propA: Number,
    // 多种类型
    propB: [String, Number],
    // 必传且是字符串
    propC: {
      type: String,
      required: true
    },
    // 数字,有默认值
    propD: {
      type: Number,
      default: 100
    },
    // 数组/对象的默认值应当由一个工厂函数返回
    propE: {
      type: Object,
      default: function () {
        return { message: 'hello' }
      }
    },
    // 自定义验证函数
    propF: {
      validator: function (value) {
        return value > 10
      }
    }
  }
})

type 可以是下面原生构造器:

String
Number
Boolean
Function
Object
Array

自定义事件

子组件要把数据传递回去
每个 Vue 实例都实现了事件接口(Events interface),即:

使用 on(eventName) 监听事件 使用emit(eventName) 触发事件

非父子组件通信

有时候非父子关系的组件也需要通信。在简单的场景下,使用一个空的 Vue 实例作为中央事件总线:

var bus = new Vue()
// 触发组件 A 中的事件
bus.$emit('id-selected', 1)
// 在组件 B 创建的钩子中监听事件
bus.$on('id-selected', function (id) {
  // ...
})

动态组件

多个组件可以使用同一个挂载点,然后动态地在它们之间切换。使用保留的 <component>元素,动态地绑定到它的 is 特性:

var vm = new Vue({
  el: '#example',
  data: {
    currentView: 'home'
  },
  components: {
    home: { /* ... */ },
    posts: { /* ... */ },
    archive: { /* ... */ }
  }
})
<component v-bind:is="currentView">
  <!-- 组件在 vm.currentview 变化时改变! -->
</component>

keep-alive把切换出去的组件保留在内存中,可以保留它的状态或避免重新渲染。

<keep-alive>
  <component :is="currentView">
    <!-- 非活动组件将被缓存! -->
  </component>
</keep-alive>

异步组件

Vue.component('async-example', function (resolve, reject) {
  setTimeout(function () {
    resolve({
      template: '<div>I am async!</div>'
    })
  }, 1000)
})

递归组件

调用自己,只有当它有 name 选项时才可以。

内联模版

如果子组件有 inline-template 特性,组件将把它的内容当作它的模板,而不是把它当作分发内容。这让模板更灵活。

<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>

X-Templates

另一种定义模版的方式是在 JavaScript 标签里使用 text/x-template 类型,并且指定一个id。

<script type="text/x-template" id="hello-world-template">
  <p>Hello hello hello</p>
</script>
Vue.component('hello-world', {
  template: '#hello-world-template'
})
上一篇 下一篇

猜你喜欢

热点阅读