Vue组件使用

作者: 蓝枫 | 来源:发表于2018-12-17 09:55 被阅读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>
  • data选项必须是一个函数,每次点击都会创建一个新的实例,每个实例中data数据都是独立的

通过 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 的 <component> 元素加一个特殊的 is 特性来实现动态组件
    <component v-bind:is="currentTabComponent"></component>在线链接
  • 使用keep-alive保持组件的现有状态,不会因为切换导致组件重新渲染。
    <keep-alive> 要求被切换到的组件都有自己的名字,不论是通过组件的 name 选项还是局部/全局注册

异步组件

为了简化,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
})

相关文章

网友评论

    本文标题:Vue组件使用

    本文链接:https://www.haomeiwen.com/subject/lyhqkqtx.html