Custom instruction
<template>
<div class="hello">
<input v-focus="name" />
</div>
</template>
<script>
export default {
data() {
return {
name: '我是名字',
}
},
directives: {
focus: {
inserted: function (el, binding) {
// 指令的定义
//el为绑定元素,可以对其进行dom操作
el.focus()
console.log(binding) //一个对象,包含很多属性属性
},
},
},
}
</script>
Custom event
Can be used to pass by value
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<meta http-equiv='X-UA-Compatible' content='ie=edge'>
<title>Document</title>
</head>
<body>
<div id='app'>
<!-- *父监听子发生的事件 -->
<cpn @itemclick="cpnclick"></cpn>
</div>
<!-- 子组件 -->
<template id="cpn">
<div>
<!-- *把数据传过去,注意写item -->
<button v-for="item in categories" @click="btnclick(item)">{
{
item.name}}</button>
</div>
</template>
<script src='../js/vue.js'></script>
<script>
//定义子组件
const cpn = {
template: '#cpn',
data() {
//这里dada是一个函数
return {
categories: [
{
id: 'aaa', name: '家用电器' },
{
id: 'bbb', name: '手机电脑' },
{
id: 'ccc', name: '汽车用品' },
{
id: 'ddd', name: '个人清洁' }
]
}
},
methods: {
// *
btnclick(item) {
// console.log(item)
this.$emit('itemclick',item)//通过$emit自定义一个事件itemclick(名字随便写),item是传过去的数据
}
},
}
//父组件
const app = new Vue({
el: '#app',
data: {
},
components: {
cpn,
},
methods:{
//*监听子组件传过来的数据
cpnclick(item){
// 这个item可以随便取名字
// console.log(1111)
console.log('cpnclick',item)
}
}
})
</script>
</body>
</html>