Vue 子组件利用父组件数据/props初始化data及问题详解

接上篇:Vue 自定义父组件向自定义子组件传值详解

props: ['initialCounter'],
data: function () {
  return {
    counter: this.initialCounter
  }
}

这是官网给出的示例,

对子组件改写,部分代码如下:

<Form>
  <FormItem>
    <Label>
      用户名
    </Label>
    <Input type="text" placeholder="请输入用户名" v-model="userDetailOfParent.userName"/>
  </FormItem>
  <FormItem>
    <Label>
      登录名
    </Label>
    <Input type="text" placeholder="请输入登录名" v-model="userDetailOfParent.loginName"/>
  </FormItem>
  <FormItem>
    <Label>
      密码
    </Label>
    <Input type="password" placeholder="请输入密码" v-model="userDetailOfParent.password"/>
  </FormItem>
</Form>
data() {

  return {

    // 利用父组件数据初始化显示
    userDetailOfParent: this.userDetailOfSon,

  }

},

props: {

  /**
   * 接收父组件传递的弹窗配置
   */
  userModalConfig: {},

  /**
   * 接收父组件传递的弹窗数据
   */
  userDetailOfSon: {},

},

但是运行后发现所有输入框显示为空,考虑弹窗界面渲染时data只执行一次,所以接收数据后未刷新导致输入框显示空,增加代码如下:

watch: {

  userDetailOfSon: function (newVal, oldVal) {
    this.userDetailOfParent = newVal;
  },

},

运行,显示正常

*关于自组件中props和data区别:

子组件中的data数据,不是通过父组件传递的是子组件私有的,是可读可写的。

子组件中的所有 props中的数据,都是通过父组件传递给子组件的,是只读的。

参考:https://segmentfault.com/a/1190000017149162 

发布了65 篇原创文章 · 获赞 8 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/u012382791/article/details/100627793