如何在Vue中通过Id获取元素? [英] How to get an Element by Id in Vue?

查看:27
本文介绍了如何在Vue中通过Id获取元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个外部 Element 在 Vue 中,使用 getElementById():

new Vue({el: "#vue",数据: {helloElement: document.getElementById('hello')}})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.js"></script><div id="你好">你好

<div id="vue">{{helloElement}}

这给我带来了一个空的 Element,但不是一个 null - 这表明查询部分成功(找到了一些东西).

这实际上是我面临的一个更普遍问题的 POC:能够从 Vue 组件中获取外部 Element(例如容器 div)(这给我带来了一个 null,其中 文档说是未找到元素时的响应).

是否可以从 Vue 对象或组件内部查询 DOM 中存在的外部 Element?

解决方案

如您所见,这是可能的.但请注意,如果您想要这样的东西,您的应用可能设计得很糟糕,并且您为 XSS 攻击创建了入口点.

new Vue({el: "#vue",数据: {helloElement: document.getElementById('hello').outerHTML}})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script><div id="你好">你好

<div id="vue" v-html="helloElement"></div>

I would like to get an outer Element in Vue, using getElementById():

new Vue({
  el: "#vue",
  data: {
    helloElement: document.getElementById('hello')
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.js"></script>
<div id="hello">
  hello
</div>
<div id="vue">
  {{helloElement}}
</div>

This brings me an empty Element, but not a null - which suggests that the query was partially successful (something was found).

This is actually a POC for a more general problem I face: the ability to get an outer Element (say, a container div) from within a Vue component (this brings me a null, which the documentation says to be the response when the element was not found).

Is it possible, from within a Vue object or component, to query an outside Element present in the DOM?

解决方案

It is possible, as you can see. But be warned, that if you want something like this, your app is probably bad designed and you created entry poin for XSS attack.

new Vue({
  el: "#vue",
  data: {
    helloElement: document.getElementById('hello').outerHTML
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<div id="hello">
  hello
</div>
<div id="vue" v-html="helloElement"></div>

这篇关于如何在Vue中通过Id获取元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆