1父传子
1.在子组件的标签上,定义随意的属性名,属性值为父组件要传给子组件的值
比如 <lqz :urls="url" :myshow="true"></lqz>
2.子组件要接收父组件传来的属性
props: ['urls', 'myshow'] //用于接收lqz标签的属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="./js/vue.js"></script>
</head>
<body>
<div id="app">
<h1>组件的使用</h1>
<hr>
<lqz :urls="url" :myshow="true"></lqz>
<hr>
</div>
</body>
<script>
// 2
var lqz = {
template: `
<div>
<h1>我是局部组件</h1>
<img :src="url" alt="" height="400px">
<button @click="handleCheck">点我看myshow类型</button>
</div>`,
data() {
return {}
},
methods: {
handleCheck() {
console.log(this.myshow)
console.log(typeof this.myshow)
}
},
props: ['urls', 'myshow'] //用于接收lqz标签的属性
}
// 根组件
var vm = new Vue({
el: '#app',
data: {
url: 'http://pic.imeitou.com/uploads/allimg/230331/7-230331110I0.jpg',
},
// 局部组件是定义在某个组件内,可以定义多个,只能在它父组件中使用,不能到别的地方使用
components: {
lqz,
}
})
</script>
</html>
2.子传父
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.staticfile.org/vue/2.7.0/vue.min.js"></script>
</head>
<body>
<div id="app">
<p>传递过来{{username}}</p>
<!-- @dffllflf="handEvent",dffllflf自定义的事件 ,handEvent函数名-->
<zhu @handls="handEvent"></zhu>
<!-- zhu 子组件定义的标签-->
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
username: '',
//将url传给子组件
},
methods: {
//handEvent函数是根组件的
handEvent(username){
this.username=username
}
},
//子组件
components: {
'zhu': {
data() {
return {
username:'',
}
},
template: `
<div>
<p>局部组件</p>
<input type="text" v-model="username">
<button @click="handleclick"> 传递给父组件</button>
</div>
`,
methods: {
handleclick(){
//handls属性名 触发handls代表的函数handEvent,将input输入的username传递给handEvent函数
this.$emit('handls',this.username)
}
}
}
}
})
</script>
</body>
</html>