一、全局注册自定义指令
vue3全局定义自定义指令 ,与vue2版本差别不大
// 文件级别
directive
--focus
--index.js
--index.js
main.js
// directive/foucs/index.js
// FFFocus指令名称
export default(app) => {
app.directive('FFFocus', {
mounted(el){
el.focus()
}
})
}
// directive/index.js
import Focus from './focus'
export default(app) => {
Focus(app)
}
// main.js
import { createApp } from 'vue'
import App from './App.vue'
import directive from './directive'
const app = createApp(App)
directive(app)
然后就可以在vue页面使用了
<template>
<div>
<input type="text" v-FFFocus />
</div>
</template>
1. 钩子函数
自定义指令提供的钩子函数
-
created:在绑定元素的 attribute 或事件监听器被应用之前调用。在指令需要附加在普通的 v-on 事件监听器调用前的事件监听器中时,这很有用。
-
beforeMount:当指令第一次绑定到元素并且在挂载父组件之前调用。
-
mounted:在绑定元素的父组件被挂载前调用。
-
beforeUpdate:在更新包含组件的 VNode 之前调用。
-
updated:在包含组件的 VNode 及其子组件的 VNode 更新后调用。
-
beforeUnmount:在卸载绑定元素的父组件之前调用
-
unmounted:当指令与元素解除绑定且父组件已卸载时,只调用一次。
mounted,updated 使用较多
2. 动态指令参数
// el , binding , vnode , prevVnode
<p v-pin:[direction]= "leng" />
directives:{
pin: {
mounted(el, binding){
console.log( el ) // 当前节点
console.log( binding.arg ) // direction
console.log( binding.value ) // leng
}
}
}
二、 全局注册组件
// 文件级别
components
--app
--index.vue
--index.js
main.js
// components/index.js
import APP from './app'
const components = {
install: function(Vue){
Vue.component('App', APP)
}
}
export default components
// main.js
import { createApp } from 'vue'
import App from './App.vue'
// 全局组件
import components from './components'
createApp(App).use(components).mount('#app')
<template>
<div class="home">
<App class="app" />
</div>
</template>
三、v-for循环中绑定不同点击事件
<template>
<div>
<div v-for="(item, index) in items" :key="index">
<button @click="setUpClick(item)">click me</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: ['look', 'read', 'listen']
}
},
methods: {
setUpClick(value) {
this[value]()
},
look() {
console.log('look')
},
read() {
console.log('read')
},
listen() {
console.log('listen')
}
}
}
</script>
四、v-for循环中绑定不同class属性
<div v-for="(item,index) in checkList" :key="index" :class="isMargin(item.id)">
动态绑定class:{{item.reward}}
</div>
<script>
export default {
data() {
return {
checkList:[ {id: 1, reward: 'hello'}, {id: 2, reward:'world'} ]
}
},
computed: {
// 循环中使用计算属性,必须用封闭式返回
isMargin() {
return (index) => {
if (index === 1) {
return 'in_week_top'
} else if (index === 2) {
return 'in_week_left'
}
}
}
}
}
</script>