vue.js 'document.getElementById' shorthand

有些话、适合烂在心里 提交于 2019-11-27 20:21:32

问题


Does vue.js have a shorthand for document.getElementById('#id') like JQuery's $('#id')?

If so, where is the reference for this in the docs so I can locate other information?


回答1:


Theres no shorthand way in vue 2.

Jeff's method seems already deprecated in vue 2.

Heres another way u can achieve your goal.

 var app = new Vue({
    el:'#app',
    methods: {    
        showMyDiv() {
           console.log(this.$refs.myDiv);
        }
    }
    
   });
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<div id='app'>
   <div id="myDiv" ref="myDiv"></div>
   <button v-on:click="showMyDiv" >Show My Div</button>
</div>



回答2:


You can use the directive v-el to save an element and then use it later.

https://vuejs.org/api/#vm-els

<div v-el:my-div></div>
<!-- this.$els.myDiv --->

Edit: This is deprecated in Vue 2, see 胡亚雄 answer




回答3:


Try not to do DOM manipulation by referring the DOM directly, it will have lot of performance issue, also event handling becomes more tricky when we try to access DOM directly, instead use data and directives to manipulate the DOM.

This will give you more control over the manipulation, also you will be able to manage functionalities in the modular format.




回答4:


If you're attempting to get an element you can use Vue.util.query which is really just a wrapper around document.querySelector but at 14 characters vs 22 characters (respectively) it is technically shorter. It also has some error handling in case the element you're searching for doesn't exist.

There isn't any official documentation on Vue.util, but this is the entire source of the function:

function query(el) {
  if (typeof el === 'string') {
    var selector = el;
    el = document.querySelector(el);
    if (!el) {
      ({}).NODE_ENV !== 'production' && warn('Cannot find element: ' + selector);
    }
  }
  return el;
}

Repo link: Vue.util.query




回答5:


you can find your answer in the combination of these two pages in the API:

  • REF

ref is used to register a reference to an element or a child component. The reference will be registered under the parent component’s $refs object. If used on a plain DOM element, the reference will be that element

  • vm.$refs

An object that holds child components that have ref registered.



来源:https://stackoverflow.com/questions/36970062/vue-js-document-getelementbyid-shorthand

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!