Vue.js基础
2022/5/26原创大约 2 分钟约 529 字
Vue.js基础应用
自定义指令
局域指令
Vue.directive('focus', {
// 当被绑定的元素插入到 DOM 中时……
inserted: function (el) {
// 聚焦元素
el.focus()
}
})
局部指令
directives: {
focus: {
// 指令的定义
inserted: function (el) {
el.focus()
}
}
}
使用指令
<input v-focus>
组件传值
.sync
.sync修饰符: 首先我们知道,父组件通过绑定属性的方式向子组件传值,而在子组件中可以通过$emit向父组件通信,通过这种间接的方式改变父组件的data,从而实现子组件改变props的值。比如向下边这这样:
子组件使用$emit向父组件发送事件:
this.$emit('update:title', newTitle)
父组件监听这个事件并更新一个本地的数据title:
<text-document
:title="title"
@update:title="val => title = val"
></text-document>
为了方便这种写法,vue提供了.sync修饰符,说白了就是一种简写的方式,我们可以将其当作是一种语法糖,比如v-on: click可以简写为@click。而上边父组件的这种写法,换成sync的方式就像下边这样:
<text-document
:title.sync="title"
></text-document>
有没有发现很清晰,而子组件中我们的写法不变,其实这两种写法是等价的,只是一个语法糖而已,如果到这里你还不太明白。下边是个完整的demo,可以copy自己的项目中尝试一下。相信你会恍然大悟。 父组件:
<template>
<div>
<child :name.sync="name"></child>
<button @click="al">点击</button>
<button @click="change">改变</button>
</div>
</template>
<script>
import child from './child'
export default {
name: 'list',
components: {
child
},
data () {
return {
listItems: ['buy food', 'play games', 'sleep'],
name: 'xiaoming'
}
},
methods: {
al() {
alert(this.name);
},
change() {
this.name = '123';
}
}
}
</script>
子组件:
<template>
<div>
<input :value="name" @input="abc" type="text">
</div>
</template>
<script>
export default {
props: {
name: {
type: String,
required: true
}
},
methods: {
abc(e) {
console.log(e.target.value);
this.$emit('update:name', e.target.value);
}
}
}
</script>
获取客户端宽度
document.body.getBoundingClientRect().width
事件监听器
window.addEventListener(type,function)
详情
resize:窗体大小事件
scroll:滚动事件