Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

将多个属性传递给 Vue 组件的几种方式 #218

Open
husky-dot opened this issue Apr 9, 2020 · 0 comments
Open

将多个属性传递给 Vue 组件的几种方式 #218

husky-dot opened this issue Apr 9, 2020 · 0 comments

Comments

@husky-dot
Copy link
Owner

作者:Jover Morales

译者:前端小智

来源:alligator

点赞再看,养成习惯

本文 GitHub https://github.com/qq449245884/xiaozhi 上已经收录,更多往期高赞文章的分类,也整理了很多我的文档,和教程资料。欢迎Star和完善,大家面试可以参照考点复习,希望我们一起有点东西。

所有使用基于组件的体系结构(如Vue和React)的开发人员都知道,创建可重用组件是很困难的,而且大多数情况下,最终会通过传入大量的属性,以便从外部更容易地控制和自定义组件。这并不坏,但是传递大量属性确实会变得有点麻烦和丑陋。

我们以 vuetify 的按钮组件为例,它是最简单的组件之一。假设我们想要在大多数情况下传递相同的属性:

<v-btn
  color='primary'
  href='https://alligator.io'
  small
  outline
  block
  ripple
>
  Hello Meat
</v-btn>

将它们放在单独的文件中是有意义的,这个文件我们取名为props.js

export const buttonProps = {
  color: 'primary',
  small: true,
  outline: true,
  block: true,
  ripple: true,
  href: 'https://alligator.io'
}

JSX 和 render 函数

由于�JSX 和 render 函数在渲染时为我们提供了更多的功能和灵活性,所以一次传递多个属性是相当容易的。

在 render 函数中:

import { buttonProps as props } from './props.js';

export default {
render: h => h(
'v-btn',
{ props },
'Hello Meat'
)
};

在 JSX 中:

import { buttonProps as props } from './props.js';

const data = { props }

export default {
  render: h => <v-btn {...data}>Hello Meat</v-btn>
};

使用 Vue.js 模板

使用Vue template怎么样?不用担心,那也是可能的。我们所需要做的就是使用v-bind指令。对于必须在组件的data选项中定义的对象,它将绑定所有属性

<template>
  <v-btn v-bind='buttonProps'>
    Hello Meat
  </v-btn>
</template>

<script>
  import { buttonProps } from './props.js';

  export default {
    data: () => ({ buttonProps })
  }
</script>

使用此技巧,我们无需在应用中的多个位置填充重复属性的模板,同时仍然可以使用受欢迎的模板标记。

总结

使用本文中提到的示例,可以简化将多个属性传递给组件的操作。 这对于具有很多属性的表示性和第三方组件特别有用。

注意,这里使用的示例仅仅演示。如果想制作更加灵活可用的,可以根据具体情况使用更好的方法,例如创建自己的包装器组件。


代码部署后可能存在的BUG没法实时知道,事后为了解决这些BUG,花了大量的时间进行log 调试,这边顺便给大家推荐一个好用的BUG监控工具 Fundebug

原文:https://alligator.io/vuejs/passing-multiple-properties/


交流

文章每周持续更新,可以微信搜索「 大迁世界 」第一时间阅读和催更(比博客早一到两篇哟),本文 GitHub https://github.com/qq449245884/xiaozhi 已经收录,整理了很多我的文档,欢迎Star和完善,大家面试可以参照考点复习,另外关注公众号,后台回复福利,即可看到福利,你懂的。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant