父子间访问子组件之间的信息(父传子)
子组件访问父组件之间的信息(子传父)
兄弟之间的传递(子传子)
父传子
<!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>
<script src="./node_modules/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<child :msg="num"></child>
</div>
<!-- 父传子 -->
</body>
<script>
Vue.component('child', {
template: '<h1>我是小陈陈{{msg}}</h1>',
props: ['msg']
});
var vm = new Vue({
el: '#app',
data: {
num: 100
},
methods: {}
});
</script>
</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>
<script src="./node_modules/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<child @fn="pfn"></child>
</div>
</body>
<script>
// 子组件
Vue.component('child', {
template: '<h1>我是一个组件</h1>',
data() {
return {
cmsg: 100
}
},
created() {
this.$emit('fn', this.cmsg);
}
});
// 父组件
var vm = new Vue({
el: '#app',
data: {},
methods: {
pfn(res) {
console.log(res);
}
},
});
// function test(callback) {
// const msg = '子组件的信息'
// callback(msg)
// }
// test(function (res) {
// console.log(res);
// });
</script>
</html>
props接收的属性是只读,不允许你修改
<!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>
<script src="./node_modules/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<child :num="msg" :List="list"></child>
</div>
</body>
<script>
// 子
Vue.component('child', {
template: '<h1>这是一个子组件{{num}}</h1>',
props: ['num'],
created() {
// this.num = '修改了';
this.list = [];
}
});
// 父
var vm = new Vue({
el: '#app',
data: {
msg: 100,
list: ['小陈陈', '小肥肥'],
},
methods: {}
});
</script>
</html>
网友评论