Vue ref属性
-
被用来给元素或子组件注册引用信息(id的替代者)
-
应用在html标签上获取的是真实DOM元素,应用在组件标签上是组件实例对象(vc)
-
使用方式:
-
打标识:
<h1 ref="xxx">.....</h1>
或<HelloWorld ref="xxx"></HelloWorld>
-
获取:
this.$refs.xxx
-
<template>
<div id="app">
<h1 ref="title"></h1>
<HelloWorld ref="content" msg="Welcome to Your Vue.js App" />
<button @click="click">click</button>
</div>
</template>
<script>
import HelloWorld from "./components/HelloWorld.vue";
export default {
name: "App",
data() {
return {
info: "HelloWorld!",
};
},
methods: {
click() {
console.log(this.$refs);
this.$refs.title.style.color = "red"; // 改变标题文字颜色
console.log(this.$refs.content.msg); // ref属性绑定组件可以获取vc对象
},
},
components: {
HelloWorld,
},
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
font-smoothing: antialiased;
osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
阅读剩余
THE END