Vue 自定义父组件向自定义子组件传值详解

1.自定义子组件,示例代码如下:

<template>
  <div>
    <Form>
      <FormItem>
        <Label>
          用户名
        </Label>
        <Input type="text" placeholder="请输入用户名" :value="userDetail.userName"/>
      </FormItem>
      <FormItem>
        <Label>
          登录名
        </Label>
        <Input type="text" placeholder="请输入登录名" :value="userDetail.loginName"/>
      </FormItem>
      <FormItem>
        <Label>
          密码
        </Label>
        <Input type="password" placeholder="请输入密码" :value="userDetail.password"/>
      </FormItem>
    </Form>
  </div>
</template>

<script>
  export default {
    name: "SystemUserDetail",

    props: {

      userDetail: {

        userName: "",
        loginName: "",
        password: "",

      }

    },

  }
</script>

<style scoped>

</style>

*注意:如果参考官网示例(示例直接将注册和templete写在了一起,这里的示例是拆开引入的)

https://cn.vuejs.org/v2/guide/components.html#%E9%80%9A%E8%BF%87-Prop-%E5%90%91%E5%AD%90%E7%BB%84%E4%BB%B6%E4%BC%A0%E9%80%92%E6%95%B0%E6%8D%AE

Vue.component('blog-post', {
props: ['title'],
template: '<h3>{{ title }}</h3>'
})

使用

value="{{userDetail.userName}}"

会提示:

Interpolation inside attributes has been removed. Use v-bind or the colon shorthand instead. For example, instead of <div id="{{ val }}">, use <div :id="val">.

所以改写为:

:value="userDetail.userName"

官网示例是props: ['...'],

这里是把userName等放到了userDetail,所以用的是props: { ... },

2.自定义父组件,关键代码如下:

// 引入
import SystemUserDetail from "./SystemUserDetail.vue"
// 注册
components: {

  SystemUserDetail,

}
<!-- 应用(这里的组件名SystemUserDetail和userDetail变成了system-user-detail和user-detail形式,可参考官网:https://cn.vuejs.org/v2/guide/components-props.html#Prop-%E7%9A%84%E5%A4%A7%E5%B0%8F%E5%86%99-camelCase-vs-kebab-case,而这里的userDetail是父组件的data定义,和子组件无关)-->
<system-user-detail
  v-bind:user-detail="userDetail"
></system-user-detail>
// 父组件data定义
data() {
  return {
    // 向弹窗传递数据
    userDetail: {},
}
},
// 父组件方法体中赋值相关代码
this.userDetail = {
  userName: this.userListData[index].userName,
  loginName: this.userListData[index].loginName,
  password: this.userListData[index].password,
}

以上学习笔记,仅供参考,欢迎交流指正

参考:

https://cn.vuejs.org/v2/guide/components.html#%E9%80%9A%E8%BF%87-Prop-%E5%90%91%E5%AD%90%E7%BB%84%E4%BB%B6%E4%BC%A0%E9%80%92%E6%95%B0%E6%8D%AE

https://cn.vuejs.org/v2/guide/components-props.html

https://www.cnblogs.com/amunamuna/p/8872979.html

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

猜你喜欢

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