zoukankan      html  css  js  c++  java
  • Vue的四种特殊attribute:is key ref v-slot (更新中)

    is的用法
    <!DOCTYPE html> <html> <head> <title>Dynamic Components Example</title> <script src="https://unpkg.com/vue"></script> <style> .tab-button { padding: 6px 10px; border-top-left-radius: 3px; border-top-right-radius: 3px; border: 1px solid #ccc; cursor: pointer; background: #f0f0f0; margin-bottom: -1px; margin-right: -1px; } .tab-button:hover { background: #e0e0e0; } .tab-button.active { background: #e0e0e0; } .tab { border: 1px solid #ccc; padding: 10px; } </style> </head> <body> <div id="dynamic-component-demo" class="demo"> <button v-for="tab in tabs" v-bind:key="tab" v-bind:class="['tab-button', { active: currentTab === tab }]" v-on:click="currentTab = tab" > {{ tab }} </button> <component v-bind:is="currentTabComponent" class="tab"></component> </div> <script> Vue.component("tab-home", { template: "<div>Home component</div>" }); Vue.component("tab-posts", { template: "<div>Posts component</div>" }); Vue.component("tab-archive", { template: "<div>Archive component</div>" }); new Vue({ el: "#dynamic-component-demo", data: { currentTab: "Home", tabs: ["Home", "Posts", "Archive"] }, computed: { currentTabComponent: function() { return "tab-" + this.currentTab.toLowerCase(); } } }); </script> </body> </html>

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

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


    ref的用法

      1、ref 加在普通的元素上,用this.ref.name 获取到的是dom元素

      2、ref 加在子组件上,用this.ref.name 获取到的是组件实例,可以使用组件的所有方法。

      3、如何利用 v-for 和 ref 获取一组数组或者dom 节点

    注意点:

           1、ref 需要在dom渲染完成后才会有,在使用的时候确保dom已经渲染完成。比如在生命周期 mounted(){} 钩子中调用,或者在 this.$nextTick(()=>{}) 中调用。在生命周期mounted之前的钩子函数中去调用           会获取不到,原因是DOM节点都没有生成this.refs的组件在v-if为false的父节点下,导致这个子组件未渲染,所以获取不到。组件已经渲染成功才能调用组件的数据。而不是页面加载完成后就一定能获取到

      2、如果ref 是v-for循环出来的,有多个重名,那么ref的值会是一个数组 ,此时要拿到单个的ref 只需要循环就可以了

      比如: <Form v-for="item in list" ref="form"></Form> 这种情况,你可以直接遍历form,然后操作。

      也可以 <Form v-for="item in list" :ref="'form'+item.key"></Form> ,然后取值的时候遍历list,

       this.list.forEach((item,index) => {

          this.$refs['form'+index][0]; //注意:这里要加个[0],因为v-for生成的ref都是数组

        })

     参考文档:https://blog.csdn.net/fz_leaves/article/details/112171188
  • 相关阅读:
    我总结的面试题系列:kafka
    RabbitMQ大厂面试题
    [Algorithm] 并查集
    [LintCode] 编辑距离
    [LeetCode] Length of Longest Fibonacci Subsequence
    [LintCode] 交叉字符串
    [LeetCode] Permutation Sequence
    Permutation Sequence
    [LeetCode] Next Permutation
    [LeetCode] Longest Palindromic Substring
  • 原文地址:https://www.cnblogs.com/xuzhenlei/p/15162562.html
Copyright © 2011-2022 走看看