<template>
<div>
<!-- 指令的生命周期 -->
<input type="text"><br>
<input type="text" v-focus ><br>
<input type="text"><br>
</div>
</template>
<script>
export default {
directives:{
/*下面这个写法是语法糖的写法,其触发时间是dom元素创建和更新时
focus(el){
// focus藏在原型->原型->原型里有focus的方法
el.focus();
}
}
}
*/
/*DOM元素:先创建->设置各种属性->添加到页面
比如创建按钮
1.创建元素:const.btn=document.createElement("button")
2.设置各种属性:比如btn.id='btn'
3.添加到页面:比如box.appendChild(btn)
*/
focus:{
//自选生命周期,来触发函数
inserted(el){
//insert:代表dom元素插入到页面显示
el.focus();
}
},
}
}
</script>
<style lang="scss" scoped>
</style>
<template>
<div>
<input type="text"><br>
<input type="text"><br>
<input type="text" ref="a"><br>
<button @click="doFocus">获得焦点</button>
<!-- 点击按钮让p标签颜色变红 -->
<p ref="b">hello</p>
</div>
</template>
<script>
export default {
/* 需求:点击按钮让第二个输入框获取焦点
也就是点击按钮调用focus方法*/
methods:{
doFocus(){
/*
下面这个是原生dom的查询写法
const inp=document.querySelectorAll("input")[2];
inp.focus();
*/
//使用ref属性可以把变量绑定在dom元素上 变量存储在$refs
console.log("$ref:",this.$refs);
this.$refs.a.focus()
this.$refs.b.style.color="red"
}
},
}
</script>
<style lang="scss" scoped>
</style>
<template>
<div>
<button @click="b">123</button>
<!-- 点击按钮 改p标签的颜色 -->
<p ref="a">456</p>
</div>
</template>
<script>
export default {
methods:{
b(){
this.$refs.a.style.color="red"
}
}
}
</script>
<style lang="scss" scoped>
</style>