整体效果如下:
警告部分:
完整代码如下:
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>Props探索</title>
</head>
<body>
<div id="app"> <!-- 父实例 -->
to-child: {{ message }}
<br><br>
<my-component :to-child='message1' :tochild2='message2'></my-component> <!-- 子组件 -->
<my-component2 :object='object' :to-child='message1'> <!-- 子组件 -->
<button @click="handlechange">change {{ object.changeName }}</button>
</my-component2>
<my-component3 :prop-number='isnumber' :prop-string='isstring'> </my-component3> <!-- 子组件 -->
</div>
</body>
<script src="vue开发.js"></script> <!-- vue开发测试版,可以在官网下载-->
<script>
// <!-- to-child tochild2 定义传给子组件的名字, message 定义传给子组件的信息内容 -->
// <!-- 子组件引用父实例的数据,在子组件里面用props,声明引用(toChild , tochild2) -->
// <!-- 注意: 实例上,to-Child 和 tochild2 的定义,在实例(html)上使用连接符’-‘时,子组件(js 或 script)引用需要使用驼峰式命名法 -->
// <!-- massage的信息内容,在父实例上赋值添加 -->
var component1 = Vue.component('my-component',{ // <!-- 子组件 -->
props:['toChild','tochild2'],
template: '<div> 子组件1:<br> to-child: {{ toChild }} \
<br> tochild2: {{ tochild2 }} \
<br> 子组件里修改父实例的数据(全部大写): {{ message3 }}</div>',
// <!-- 在子组件里面不能直接修改通过props从父实例上获取的数据,而是通过添加一个计算属性( computed )返回一个’计算‘后的数据( message3 ) -->
computed:{
message3: function(){ // ’计算‘修改 父实例的to-child里面的内容:message1,获得新的数据 message3
return this.toChild.trim().toUpperCase()
},
},
})
var component2 = Vue.component('my-component2',{ // <!-- 子组件 -->
template: '<p>子组件2:<br>{{ childObject.number }} is {{ childObject.name }}\'s number.\
<br><input v-model="childObject.name" type="text">\
<slot>父实例没有内容(已有button)时,显示这段文字</slot>\
</p>',
props: ['object'],
// <!-- 将子组件的childObject与父实例的object双向绑定 -->
// <!-- 子组件的input可以输入改变双向数据 -->
// <!-- 父实例的methods也可以改变双向数据 -->
// 注意在 JavaScript 中对象和数组是通过引用传入的,所以对于一个数组或对象类型的 prop 来说,在子组件中改变这个对象或数组本身将会影响到父组件的状态。
data: function () {
return {
childObject: this.object,
}
}
})
var component3 = Vue.component('my-component3',{ // <!-- 子组件 -->
template: '<p>子组件3:<br> Number: {{ propNumber }} <br> String: {{ propString }} </p>',
// <!-- 对父实例的数据进行验证,不符合时,会在调试模式的’console’的最上面生成一个警告 -->
props:{
// <!-- 验证数据是否是数字,不是数字给出警告,不是数字时也不会是‘5’, 只有当propNumber(父实例中的isnumber)没有定义时,才会是默认值‘5’ -->
propNumber : {
type: Number,
default: 5,
},
propString : String,
}
})
var app = new Vue({ // <!-- 父实例 -->
el: '#app',
data:{
message: 'Lovell',
message1: 'Hi, Lovell',
message2: 'Lovell, hi!',
object: {
name: 'Lovell',
number: '2016141034',
changeName:"L.W.",
},
isnumber: 'a12345',
isstring: 'a12345',
},
methods:{
handlechange: function(){
this.object.changeName = 'L.W.';
this.object.name = this.object.changeName;
}
},
});
</script>
</html>