zoukankan      html  css  js  c++  java
  • vue学习12

    接上篇:

    组件的基础

    在组件上使用 v-model

    自定义事件也可以用于创建支持 v-model 的自定义输入组件。记住:

    <input v-model="searchText">

    等价于:

    <input
      v-bind:value="searchText"
      v-on:input="searchText = $event.target.value"
    >

    当用在组件上时,v-model 则会这样:

    <custom-input
      v-bind:value="searchText"
      v-on:input="searchText = $event"
    ></custom-input>

    为了让它正常工作,这个组件内的 <input> 必须:

    • 将其 value attribute 绑定到一个名叫 value 的 prop
    • 在其 input 事件被触发时,将新的值通过自定义的 input 事件抛出

    写成代码之后是这样的:(子组件)

    Vue.component('custom-input', {
      props: ['value'],
      template: `
        <input
          v-bind:value="value"
          v-on:input="$emit('input', $event.target.value)"
        >
      `
    })

    现在 v-model 就应该可以在这个组件上完美地工作起来了:

    <custom-input v-model="searchText"></custom-input>

    通过插槽分发内容

    和 HTML 元素一样,我们经常需要向一个组件传递内容,像这样:

    <alert-box>
      Something bad happened.
    </alert-box>

    可能会渲染出这样的东西:

     幸好,Vue 自定义的 <slot> 元素让这变得非常简单:

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

    只要在需要的地方加入插槽就行了——就这么简单!

    动态组件

    有的时候,在不同组件之间进行动态切换是非常有用的,比如在一个多标签的界面里:

     上述内容可以通过 Vue 的 <component> 元素加一个特殊的 is attribute 来实现:

    <!-- 组件会在 `currentTabComponent` 改变时改变 -->
    <component v-bind:is="currentTabComponent"></component>

    在上述示例中,currentTabComponent 可以包括

    • 已注册组件的名字,或
    • 一个组件的选项对象

    请留意,这个 attribute 可以用于常规 HTML 元素,但这些元素将被视为组件,这意味着所有的 attribute 都会作为 DOM attribute 被绑定。对于像 value 这样的 property,若想让其如预期般工作,你需要使用 .prop 修饰器。

    解析 DOM 模板时的注意事项

    有些 HTML 元素,诸如 <ul><ol><table> 和 <select>,对于哪些元素可以出现在其内部是有严格限制的。而有些元素,诸如 <li><tr> 和 <option>,只能出现在其它某些特定的元素内部。

    这会导致我们使用这些有约束条件的元素时遇到一些问题。例如:

    <table>
      <blog-post-row></blog-post-row>
    </table>

    这个自定义组件 <blog-post-row> 会被作为无效的内容提升到外部,并导致最终渲染结果出错。幸好这个特殊的 is attribute 给了我们一个变通的办法:

    <table>
      <tr is="blog-post-row"></tr>
    </table>

    需要注意的是如果我们从以下来源使用模板的话,这条限制是不存在的:

    • 字符串 (例如:template: '...')
    • 单文件组件 (.vue)
    • <script type="text/x-template">

    继续。。

  • 相关阅读:
    Java如何编写自动售票机程序
    install windows service
    redis SERVER INSTALL WINDOWS SERVICE
    上传文件
    This problem will occur when running in 64 bit mode with the 32 bit Oracle client components installed.
    解决Uploadify上传控件加载导致的GET 404 Not Found问题
    OracleServiceORCL服务不见了怎么办
    Access to the temp directory is denied. Identity 'NT AUTHORITYNETWORK SERVICE' under which XmlSerializer is running does not have sufficient permiss
    MSSQL Server 2008 数据库安装失败
    数据库数据导出成XML文件
  • 原文地址:https://www.cnblogs.com/zxh06820/p/13577070.html
Copyright © 2011-2022 走看看