我的需求
有些时候,我们需要获取组件的DOM元素
有些小伙伴会说,这还不简单
直接使用this.$ref.xx不就可以了吗
我们来看一下,是不是我们想的那样简单
组件内容
<template> <div class="demo"> <h2>我是组件</h2> <div>我是组件中的数据</div> </div> </template>
使用组件的页面
<template> <div> 我是页面测试一 <testcom ref="testRef"></testcom> </div> </template> <script> import testcom from "../components/test-com.vue" export default { components:{ testcom:testcom }, mounted(){ console.log('获取组件内的DOM',this.$refs.testRef); } } </script>
现在的实际结果
我想在这个页面内,获取组件内的DOM元素
也就是获取
<div> 我是页面测试一 <testcom ref="testRef"></testcom> </div>
实际上压根获取的就是这样的
我们并没有获取到组件内的DOM元素。
而是获取的是Vue的组件
那要怎么样才可以获取组件内的元素呢
解决办法使用$el
<template> <div> 我是页面测试一 <testcom ref="testRef"></testcom> </div> </template> <script> import testcom from "../components/test-com.vue" export default { components:{ testcom:testcom }, mounted(){ console.log('获取组件内的DOM',this.$refs.testRef.$el); } } </script>
需求描述
有些时候我们需要封装组件
封装组件的时候,
我们需要属性直接设置在某一个指定的元素上。
<template> <div> 我是测试页面 <testcom type="text"></testcom> <testcom type="password"></testcom> </div> </template>
组件
<template> <div class="demo"> <input name="" id=""> </div> </template>
实际结果
属性结果直接被添加到跟元素上去了。
因为这个是vue规定的
我们如何让属性设置在指定的元素上面呢?
我们可以使用inheritAttrs
官网对:inheritAttrs的解释
如果你不希望组件的根元素有继承特性,你可以在组件的选项中设置 inheritAttrs: false。
解决办法inheritAttrs的使用
<template> <div class="demo"> //动态绑定到需要的元素上 <input v-bind="$attrs" name="" id=""> </div> </template> <script> export default { //表示不添加在组件的根元素上 inheritAttrs:false } </script>