标签:zhang new 自定义 data eth tle rop javascrip 表达
一、父子组件通讯父传子:
1、父用子的时候通过属性传递
2、子要声明props:[‘属性名‘]接收
3、子组件template中直接用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script type="text/javascript" src="vue.js"></script>
<div id="app"></div>
<script type="text/javascript">
// 父传子
var child = {
template: `
<div>我是子组件
{{sendToChild}}
</div>
`,
props: [‘sendToChild‘]
}
var parent = {
template: `
<div>我是父组件
<child sendToChild="send"></child>
</div>
`,
components: {
child
}
}
new Vue({
el: ‘#app‘,
template: `
<div>
<parent></parent>
</div>
`,
components: {
parent
}
})
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script type="text/javascript" src="vue.js"></script>
<div id="app"></div>
<script type="text/javascript">
// 父传子
var child = {
template: `
<div>我是子组件
{{sendToChild}}
</div>
`,
props: [‘sendToChild‘]
}
var parent = {
template: `
<div>我是父组件
<child v-bind:sendToChild="send"></child>
</div>
`,
components: {
child
},
data() {
return {
send:
{name: ‘zhangsan‘, age: 12}
}
}
}
new Vue({
el: ‘#app‘,
template: `
<div>
<parent></parent>
</div>
`,
components: {
parent
}
})
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script type="text/javascript" src="vue.js"></script>
<div id="app"></div>
<script type="text/javascript">
// 子传父
var child = {
template: `
<div>我是子组件
<button @click="sendToParent">点我送礼物给爸爸</button>
</div>
`,
methods:{
sendToParent(){
// 子传父表达式this.$emit(‘父组件接收事件名‘,‘参数1‘,‘参数2‘)
this.$emit(‘hellobaba‘,‘给你带个苹果‘,‘给你带个梨‘)
}
}
}
var parent = {
// 父组件中@子传入事件名进行监听
template: `
<div>我是父组件
<child @hellobaba="myaccept"></child>
儿子给我:{{param1}},{{param2}}
</div>
`,
components: {
child
},
data(){
return {
param1:‘‘,
param2:‘‘
}
},
methods: {
myaccept(val1,val2){
this.param1 = val1
this.param2 = val2
}
}
}
new Vue({
el: ‘#app‘,
template: `
<div>
<parent></parent>
</div>
`,
components: {
parent
}
})
</script>
</body>
</html>
标签:zhang new 自定义 data eth tle rop javascrip 表达
原文地址:https://blog.51cto.com/12012821/2399322