JavaScript/vue.js/DOM元素修改:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
Kangkk​(留言 | 贡献)
第3行: 第3行:
document.getElementById("id");</syntaxhighlight>
document.getElementById("id");</syntaxhighlight>
== vue ==
== vue ==
ref 被用来给元素或子组件注册引用信息。引用信息将会注册在父组件的 $refs 对象上。如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素; 如果用在子组件上,引用就指向组件实例
<syntaxhighlight lang="html5">
<syntaxhighlight lang="html5">
<div ref=“name”></div>
<div ref=“name”></div>
第21行: 第23行:
* 如果给子组件加 ref,然后获取到该 DOM 元素之后改变相应的自定义属性的值,vue 会报错:Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "title"
* 如果给子组件加 ref,然后获取到该 DOM 元素之后改变相应的自定义属性的值,vue 会报错:Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "title"
{{Unknown}}
{{Unknown}}
=== eq ===
<syntaxhighlight lang="html5">
<li class="sidebar-list"  v-for="(item, index) in meunList"  @click="setPageMenu(index)" ref="menuItem">
    <router-link class="sidebar-a" :to="{ path: item.listLink }" >{{item.listTitle}}</router-link>
</li></syntaxhighlight>
<syntaxhighlight lang="javascript">
setPageMenu(index) {
//这个是获取当前menuItem值,用index来区分当前元素是v-for 产生的数组中的第几个数
    let getMenuText = this.$refs.menuItem[index].innerText;
}</syntaxhighlight>

2020年7月22日 (三) 04:10的版本

原生

document.getElementById("id");

vue

ref 被用来给元素或子组件注册引用信息。引用信息将会注册在父组件的 $refs 对象上。如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素; 如果用在子组件上,引用就指向组件实例

<div ref=“name”></div>
<script>
  mounted() {
    this.$refs.name.style.backgroundColor="#108ee9"
  },
  methods:{
    this.$refs.name
  }
</script>

注意:

  • 在获取相应元素之前,必须在 mounted 生命周期进行挂载,否则获取到的值为空;
  • 如果是给子组件加id并修改自定义属性,则直接会加载该子组件对应的外层div上,并不会改变该子组件原本的自定义属性的值;
  • 如果给子组件加 ref,然后获取到该 DOM 元素之后改变相应的自定义属性的值,vue 会报错:Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "title"

(来源摘自互联网示例,作者 未知)

eq

<li class="sidebar-list"  v-for="(item, index) in meunList"  @click="setPageMenu(index)" ref="menuItem">
    <router-link class="sidebar-a" :to="{ path: item.listLink }" >{{item.listTitle}}</router-link>
</li>
setPageMenu(index) {
//这个是获取当前menuItem值,用index来区分当前元素是v-for 产生的数组中的第几个数
    let getMenuText = this.$refs.menuItem[index].innerText;
}