<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>解决方案:watch、computed</title> <script src="https://cdn.bootcss.com/vue/2.5.16/vue.min.js"></script> </head> <body> <div> <user-info :user-data="user"></user-info> </div> <script> //全局组件 let userInfo = Vue.component('userInfo' ,{ name: 'user-info', props: { userData: Object }, data() { return { userName: this.userData.name } }, computed: { computedUserName(){ return this.userData.name } }, watch: { 'userData.name': function (val) {//监听props中的属性 this.userName = val; } }, template: ` <div> <div>姓名(watch):{{ userName }}</div> <div>姓名(computed):{{ computedUserName }}</div> <div>性别:{{ userData.gender }}</div> <div>生日:{{ userData.birthday }}</div> </div> ` }); //Vue实例 new Vue({ el: '#app', data: { user: { name: '', gender: '', birthday: '' } }, created(){ this.getUserData(); }, methods:{ getUserData(){ setTimeout(()=>{ this.user = { name: '于永雨', gender: '男', birthday: '1991-7' } }, 500) } }, components: { userInfo } }); </script> </body> </html>
运行结果
完美!!!
四、总结:关于Vue中props的要点
事后又仔细翻了一下关于props的文档:
大概梳理一下:
1.props是单向数据流:父组件的数据变化,通过props实时反应在子组件中,反之不然
2.不允许在子组件中直接操作props
3.可以变相操作props
(1)在data中声明局部变量,并用props初始化,弊端:局部变量不随着props更新而更新
(2)在computed中对props值转换后输出