咔叽游戏

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
查看: 467|回复: 0

[JavaScript] Vue $attrs & inheritAttr实现button禁用效果案例

[复制链接]
  • TA的每日心情
    无聊
    2019-6-2 14:11
  • 签到天数: 4 天

    [LV.2]圆转纯熟

    发表于 2020-12-19 13:38:04 | 显示全部楼层 |阅读模式
    components/Button.vue
    1. <template>
    2. <div>
    3.   <button :disabled="$attrs.disabled">点击</button>
    4. </div>
    5. </template>
    6. <script>
    7. export default {
    8.    inheritAttrs: false,
    9. }
    10. </script>
    11. <style scoped>
    12. </style>
    复制代码
    App.vue
    1. <template>
    2. <div id="app">
    3. <Parent></Parent>
    4. <Button disabled></Button>
    5. </div>
    6. </template>
    复制代码
    1. <script>
    2. import Parent from './components/Parent'
    3. import Button from './components/Button';
    4. export default {
    5. name: 'App',
    6. components: {
    7. Parent,
    8. Button
    9. }
    10. }
    11. </script>
    复制代码
    1. <style>
    2. #app {
    3. font-family: Avenir, Helvetica, Arial, sans-serif;
    4. -webkit-font-smoothing: antialiased;
    5. -moz-osx-font-smoothing: grayscale;
    6. text-align: center;
    7. color: #2c3e50;
    8. margin-top: 60px;
    9. }
    10. </style>
    复制代码
    效果截图1-inheritAttrs默认true:
    Vue $attrs & inheritAttr实现button禁用效果案例-1.jpg

    效果截图2-inheritAttrs=false:
    Vue $attrs & inheritAttr实现button禁用效果案例-2.jpg

    补充知识:vue中使用inheritAttrs实现组件的扩展性
    1、首先我们创建一个input组件
    1. <template>
    2.   <div class="inputCom-wrap">
    3.     <input v-bind="$attrs" />
    4.   </div>
    5. </template>
    6. <script lang="ts">
    7. import { defineComponent } from 'vue'
    8. export default defineComponent({
    9.   inheritAttrs:false,//不希望根直接继承特性,而是使用$attrs自定义继承,当前组件的根就是inputCom-wrap
    10.   setup () {
    11.     return {}
    12.   }
    13. })
    14. </script>
    15. <style scoped>
    16. </style>
    复制代码
    2、使用组件的时候,随便增加一些属性,如
    <inputCom type="text" class="input-a"></inputCom>
    <inputCom type="password" class="input-b"></inputCom>
    3、查看最终的渲染结果为(与props不会冲突)
    Vue $attrs & inheritAttr实现button禁用效果案例-3.jpg

    以上这篇Vue $attrs & inheritAttr实现button禁用效果案例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持咔叽论坛。

    原文地址:https://www.jb51.net/article/201538.htm

    QQ|免责声明|小黑屋|手机版|Archiver|咔叽游戏

    GMT+8, 2024-3-29 07:11

    Powered by Discuz! X3.4

    © 2001-2023 Discuz! Team.

    快速回复 返回顶部 返回列表