🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
Vue.js 支持通过 `ref` 属性来访问其它组件和 HTML 元素。并通过 `this.$refs` 可以得到组件或 HTML 元素的上下文。在大多数情况下,通过 `this.$refs`来访问其它组件的上下文是可以避免的。在使用的的时候你需要注意避免调用了不恰当的组件 API,所以应该尽量避免使用 `this.$refs`。 ### [](https://github.com/pablohpsilva/vuejs-component-style-guide/blob/master/README-CN.md#为什么-8)为什么? * 组件必须是保持独立的,如果一个组件的 API 不能够提供所需的功能,那么这个组件在设计、实现上是有问题的。 * 组件的属性和事件必须足够的给大多数的组件使用。 ### [](https://github.com/pablohpsilva/vuejs-component-style-guide/blob/master/README-CN.md#怎么做-8)怎么做? * 提供良好的组件 API。 * 总是关注于组件本身的目的。 * 拒绝定制代码。如果你在一个通用的组件内部编写特定需求的代码,那么代表这个组件的 API 不够通用,或者你可能需要一个新的组件来应对该需求。 * 检查所有的 props 是否有缺失的,如果有提一个 issue 或是完善这个组件。 * 检查所有的事件。子组件向父组件通信一般是通过事件来实现的,但是大多数的开发者更多的关注于 props 从忽视了这点。 * Props向下传递,事件向上传递!。以此为目标升级你的组件,提供良好的 API 和 独立性。 * 当遇到 props 和 events 难以实现的功能时,通过 `this.$refs`来实现。 * 当需要操作 DOM 无法通过指令来做的时候可使用 `this.$ref` 而不是 `JQuery`、`document.getElement*`、`document.queryElement`。 ~~~ <!-- 推荐,并未使用 this.$refs --> <range :max="max" :min="min" :step="1" @current-value="currentValue" ></range> ~~~ ~~~ <!-- 使用 this.$refs 的适用情况--> <modal ref="basicModal"> <h4>Basic Modal</h4> <button class="primary" @click="$refs.basicModal.hide()">Close</button> </modal> <button @click="$refs.basicModal.open()">Open modal</button> <!-- Modal component --> <template> <div v-show="active"> <!-- ... --> </div> </template> <script> export default { // ... data() { return { active: false, }; }, methods: { open() { this.active = true; }, hide() { this.active = false; }, }, // ... }; </script> ~~~ ~~~ <!-- 如果可通过 emited 来做则避免通过 this.$refs 直接访问 --> <template> <range :max="max" :min="min" :step="1" ref="range" ></range> </template> <script> export default { // ... methods: { getRangeCurrentValue() { return this.$refs.range.currentValue }, }, // ... }; </script> ~~~