• vue用组件构建应用


    组件系统是 Vue.js 另一个重要概念,因为它提供了一种抽象,让我们可以用独立可复用的小组件来构建大型应用。如果我们考虑到这点,几乎任意类型的应用的界面都可以抽象为一个组件树:

    Component Tree

    在 Vue 里,一个组件实质上是一个拥有预定义选项的一个 Vue 实例:

    // Define a new component called todo-item
    Vue.component('todo-item', {
      template: '<li>This is a todo</li>'
    })

    现在你可以在另一个组件模板中写入它:

    <ol>
      <!-- Create an instance of the todo-item component -->
      <todo-item></todo-item>
    </ol>

    但是这样会为每个 todo 渲染同样的文本,这看起来并不是很酷。应该将数据从父作用域传到子组件。来修改一下组件的定义,使得它能够接受一个 prop 字段:

    Vue.component('todo-item', {
      // The todo-item component now accepts a
      // "prop", which is like a custom attribute.
      // This prop is called todo.
      props: ['todo'],
      template: '<li>{{ todo.text }}</li>'
    })

    现在,我们可以使用 v-bind 指令将 todo 传到每一个重复的组件中:

    <div id="app-7">
      <ol>
        <!-- Now we provide each todo-item with the todo object    -->
        <!-- it's representing, so that its content can be dynamic -->
        <todo-item v-for="item in groceryList" v-bind:todo="item"></todo-item>
      </ol>
    </div>

    完整代码如下:

    Vue.component('todo-item', {
      props: ['todo'],
      template: '<li>{{ todo.text }}</li>'
    })
    var app7 = new Vue({
      el: '#app-7',
      data: {
        groceryList: [
          { text: 'Vegetables' },
          { text: 'Cheese' },
          { text: 'Whatever else humans are supposed to eat' }
        ]
      }
    })
    image

    这只是一个假设的例子,但是我们已经将应用分割成了两个更小的单元,子元素通过 props 接口实现了与父亲元素很好的解耦。我们现在可以在不影响到父应用的基础上,进一步为我们的 todo 组件改进更多复杂的模板和逻辑。

    在一个大型应用中,为了使得开发过程可控,有必要将应用整体分割成一个个的组件。在后面的教程中我们将详述组件,不过这里有一个(假想)的例子,看看使用了组件的应用模板是什么样的:

    <div id="app">
      <app-nav></app-nav>
      <app-view>
        <app-sidebar></app-sidebar>
        <app-content></app-content>
      </app-view>
    </div>
  • 相关阅读:
    android-exploitme(六):基础加密
    错误:error libGL.so: cannot open shared object file: No such file or directory
    android-exploitme(五):不安全的数据存储
    android-exploitme(四):参数篡改
    android-exploitme(三):安全连接
    android-exploitme(二):安装apk熟悉测试环境
    android-exploitme(一):生成apk
    Ubuntu rsync同步
    phantomjs + selenium headless test
    Fatal error: cannot allocate memory for the buffer pool
  • 原文地址:https://www.cnblogs.com/zsy/p/6490575.html
Copyright © 2020-2023  润新知