<!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">
<!-- 组件注册成功后,可以直接使用组件名作为标签 -->
<com></com>
</div>
<script>
// 组件配置对象
const com = {
template: `
`
}
// 1 全局注册
// Vue.component('自定义组件名', com)
// 2 局部注册(局部注册需要在对应的组件中进行注册)
const app = new Vue({
el: '#app',
components: {
// 自定义组件名: 组件配置对象
// com: com
com
}
})
</script>
</body>
</html>
组件之间的通信
<!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">
<!-- <child :a="2"></child> -->
<!-- <child a="2" b="3" c="数据"></child> -->
<child :msg="msg" @update:msg="getMsg"></child>
<child @click="函数"></child>
<!-- <p a="1"></p> -->
</div>
<script src="./vue.js"></script>
<script>
/*
Vue中组件关系分为以下两种
父子
非父子
由此得到三种通信方式
父 -> 子
只要子组件标签上有属性,那么在子组件中就一定能接收
数据是由父组件传向子组件的
父组件 传数据
找到父组件模板中的子组件标签
在子组件标签上添加属性=属性值
prop名字="值"
<子标签 a="1"></子标签>
子组件 接收数据
找到子组件的组件配置对象,
添加props属性
props: ['prop名字1', 'prop名字2']
props: {
prop名字1: 类型
}
prop当作data使用即可
子 -> 父
只要组件标签上绑定了事件,那么这个事件一定是自定义事件(想要让自定义事件触发,就必须在子组件的相关操作中触发这个事件)。如果我们想要在组件上绑定原生事件
@click.native="函数"
子组件触发
需要在子组件中的对应元素上绑定原生事件
在组件中的methods里添加对应的事件函数
在对应事件函数中触发自定义事件
父组件接收
找到父组件模板中的子组件标签
在子组件标签上绑定自定义事件
<子组件标签 @自定义事件="父methods中函数"></子组件标签>
在父组件methods中添加函数
methods: {
函数 (data) {
data就是子组件中传递过来的数据
}
}
非父子通信
需要一个公共的实例对象
const bus = new Vue()
需要传值的组件中
bus.$emit('自定义事件', 数据)
需要接受值的组件中
bus.$on('自定义事件', data => {
data就是上面的数据
})
*/
const child = {
template: `
<div>
子组件
<button @click="changeMsg">按钮</button>
{{typeof a}}
{{b}}
{{msg}}
</div>
`,
props: ['a', 'b', "msg"],
methods: {
changeMsg () {
// this.$emit('自定义事件名', '要传递的数据')
this.$emit('update:msg', '子组件中传递过去的数据')
}
}
}
Vue.component('child', child)
const app = new Vue({
el: '#app',
data: {
msg: "父组件中的数据"
},
methods: {
getMsg (data) {
console.log(data)
this.msg = data
}
}
})
</script>
</body>
</html>