上篇文章有说到默认情况下,子组件访问不到父组件的数据,但是通过props这个属性可以实现父组件和子组件之间的数据共享
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>组件之间的数据传递和数据删改</title>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<style type="text/css">
*{
list-style: none;
cursor: pointer;
}
</style>
</head>
<body>
<!-- 注意,父组件的数据改变会同步到子组件,但是基本数据类型(String、Array、Number等)只能单向(父传子)传递,只有引用类型可以双向传递 -->
<!-- 父组件调用 -->
<div id="example">
<parent></parent>
</div>
<!-- 父组件模板 -->
<template id="example01">
<div>
<h2 @click = "msg = '我是父组件改变后的数据'">{{ msg }}</h2>
<h3 @click = "obj.name = 'gzh'">点我改名换姓~{{ obj.name}} : {{ obj.age }}</h3>
<!-- 子组件调用 -->
<child :cmsg = 'msg' :clist = 'list' :cfn = 'fn' :cobj = 'obj'></child>
</div>
</template>
<!-- 子组件模板 -->
<template id="example02">
<div>
<h3 @click = "cobj.age = '18'">点我变年轻~ {{ cobj.name}} : {{ cobj.age }}</h3>
<h2 @click= "cfn('hello')">{{ cmsg }}</h2>
<ul>
<li V-for='(val , key) in clist' :key='key'>{{ val }}</li>
</ul>
</div>
</template>
<script>
// 子组件
var Child = {
template: '#example02',
props : {
cmsg : String,
clist : Array,
cfn : Function,
cobj : Object
}
}
// 父组件
var Parent = {
template : '#example01',
components : {
'child' : Child
},
data : function(){
return {
msg : '点我',
list : ['1','2','3'],
obj : {
name : 'zm',
age : 28
}
}
},
methods: {
fn : function(str){
alert(str);
}
}
}
//组件挂载
var vm = new Vue({
el: '#example',
components : {
'parent' : Parent
}
});
</script>
</body>
</html>