让前端飞

Vue组件使用

2018-12-17  本文已影响0人  蓝枫

Vue组件

组件是可复用的 Vue 实例,相当于公用方法,与 new Vue 接收相同的选项,例如 data、computed、watch、methods 以及生命周期钩子等。仅有的例外是像 el 这样根实例特有的选项

基本示例

// 注册组件
Vue.component('button-counter', {
  data: function () {
    return {
      count: 0
    }
  },
  template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
})

// html
<div id="components-demo">
  <button-counter></button-counter>
</div>

// 组件使用
new Vue({ el: '#components-demo' })

// 组件复用
<div id="components-demo">
  <button-counter></button-counter>
  <button-counter></button-counter>
  <button-counter></button-counter>
</div>

通过 Prop 向子组件传递数据

Vue组件间通信

通过事件向父级组件发送消息

Vue组件间通信

通过插槽分发内容

通过slot向一个组件传递内容

Vue.component('alert-box', {
  template: `
    <div class="demo-alert-box">
      <strong>Error!</strong>
      <slot></slot>
    </div>
  `
})

多个插槽时候使用剧名插槽,

// 命名slot
<slot name="header"></slot>
// 使用名为header的slot
 <template slot="header">
    <h1>Here might be a page title</h1>
 </template>

父组件模板的所有东西都会在父级作用域内编译;子组件模板的所有东西都会在子级作用域内编译。

动态组件 & 异步组件

动态组件

异步组件

为了简化,Vue 允许你以一个工厂函数的方式定义你的组件,这个工厂函数会异步解析你的组件定义。Vue 只有在这个组件需要被渲染的时候才会触发该工厂函数,且会把结果缓存起来供未来重渲染

Vue.component('async-example', function (resolve, reject) {
  setTimeout(function () {
    // 向 `resolve` 回调传递组件定义
    resolve({
      template: '<div>I am async!</div>'
    })
  }, 1000)
})

处理加载状态

const AsyncComponent = () => ({
  // 需要加载的组件 (应该是一个 `Promise` 对象)
  component: import('./MyComponent.vue'),
  // 异步组件加载时使用的组件
  loading: LoadingComponent,
  // 加载失败时使用的组件
  error: ErrorComponent,
  // 展示加载时组件的延时时间。默认值是 200 (毫秒)
  delay: 200,
  // 如果提供了超时时间且组件加载也超时了,
  // 则使用加载失败时使用的组件。默认值是:`Infinity`
  timeout: 3000
})
上一篇 下一篇

猜你喜欢

热点阅读