1、父变子也变
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.js"></script>
</head>
<body>
<div id="rou">
<father></father>
</div>
<template id="father">
<div>
<h3>我是父组件</h3>
<input type="text" v-model="name"/>
<hr />
<son :name="name"></son>
</div>
</template>
<template id="son">
<div>
<h3>我是子组件</h3>
<h3>从父获取的数据:{{name}}</h3>
</div>
</template>
<script>
var aj = new Vue({
el: '#rou',
data: {
type:'role'
},
components: {
'father': {
template: '#father',
data: () => {
return {
name: '父数据'
}
},
components: {
'son': {
template: '#son',
props: ['name']
}
}
},
},
})
</script>
</body>
</html>
2、子向父传递
1)使用.sync
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.staticfile.org/vue/2.3.2/vue.js"></script>
</head>
<body>
<div id="rou">
<input type="text" v-model="name"/>
<father :name.sync="name"></father>
</div>
<template id="father">
<div>
<h3>我是子组件</h3>
<h3>{{name}}</h3>
<button @click="change">子传父</button>
</div>
</template>
<script>
var aj = new Vue({
el: '#rou',
data: {
name: 'role'
},
components: {
'father': {
template: '#father',
props: ['name'],
methods: {
change(){
this.$emit('update:name', 'xcc')
}
}
},
},
})
</script>
</body>
</html>
2)通过对象属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.js"></script>
</head>
<body>
<div id="rou">
<father></father>
</div>
<template id="father">
<div>
<h3>我是父组件</h3>
<h3>{{user.name}}</h3>
<hr />
<son :user="user"></son>
</div>
</template>
<template id="son">
<div>
<h3>我是子组件</h3>
<h3>{{user.name}}</h3>
<button @click="change">子传父</button>
</div>
</template>
<script>
var aj = new Vue({
el: '#rou',
data: {
type:'role'
},
components: {
'father': {
template: '#father',
data: () => {
return {
name: '父数据',
user: {
name:'父'
}
}
},
components: {
'son': {
template: '#son',
props: ['user'],
methods: {
change() {
this.user.name = 'xcc'
}
}
},
}
},
},
})
</script>
</body>
</html>