Vue父子组件传值

Love The Way You Lie 2023-05-31 06:46 104阅读 0赞

首先创建基础项目

https://blog.csdn.net/sunt2018/article/details/102697487

然后写一个父子组件

App.vue

  1. <template>
  2. <div id="app">
  3. <!-- 导入父组件 -->
  4. <!-- 默认规则 必须大写MP 使用小写m-p,-隔开 -->
  5. <m-parent></m-parent>
  6. </div>
  7. </template>
  8. <script>
  9. import MParent from './views/Parent' //d导入父组件
  10. export default {
  11. components:{
  12. MParent,//注册父组件
  13. },
  14. }
  15. </script>

在views 创建父子组件

Parent.vue

首字母大写,也是大多数默认规则

  1. <template>
  2. <div>
  3. <h1>Parent父组件</h1>
  4. <m-child></m-child>
  5. </div>
  6. </template>
  7. <script>
  8. import MChild from './Child'
  9. export default{
  10. components:{
  11. MChild,
  12. },
  13. }
  14. </script>
  15. <style scoped>
  16. </style>

Child.vue

  1. <template>
  2. <div>
  3. <h3>child组件</h3>
  4. </div>
  5. </template>
  6. <script>
  7. export default{
  8. }
  9. </script>
  10. <style>
  11. </style>

父子组件间的传值

  • props/$emit
  • $parent/children
  • $ref

第一种传值方式,绑定属性

  1. <!-- 父组件中的 子组件上写 -->
  2. <m-child v-bind:msg="'from Parent msg'"></m-child>
  3. <!-- 使用v-bind , 字段参数是msg,传入内容为字符串 -->
  4. <!-- 子组件中接收 -->
  5. <template>
  6. <div>
  7. <h3>child</h3>
  8. <!-- 使用 -->
  9. <h5>{
  10. {msg}}</h5>
  11. </div>
  12. </template>
  13. <script>
  14. export default{
  15. props:{//接收参数
  16. msg:{
  17. type:String,//类型
  18. default:'' // 默认值
  19. }
  20. }
  21. }
  22. </script>

反向传值,子组件向父组件传值,一般是通过事件触发

  1. <!-- 子组件写一个点击事件 -->
  2. <button @click="passMsg">走你</button>
  3. <script>
  4. export default{
  5. methods:{
  6. passMsg(){
  7. this.$emit('showMsg','i am from child')
  8. // 传一个自定义的事件 showMsg,值是 i am from child
  9. }
  10. }}
  11. </script>
  12. <!-- 父组件,使用@事件=“事件” 去监听 -->
  13. <m-child v-bind:msg="'from Parent msg'" @showMsg="showMsg"></m-child>
  14. export default{
  15. data(){
  16. return {
  17. msg:'',// 通过msg去接收监听的参数
  18. }
  19. },
  20. components:{
  21. MChild,
  22. },
  23. methods:{//监听方法,val是子组件传入的值
  24. showMsg(val){
  25. this.msg = val
  26. }
  27. }
  28. }
  29. </script>

第二种方法,使用 $parent/ $children

  1. 需要创建一个钩子
  2. mounted(){
  3. this.$children[0].msg //要手动寻找索引,然后再找信息
  4. //还可以触发方法
  5. }

第三种方法 refs

  1. this.refs.child
  2. 和第二种方法一样,都是一个数组
  3. 需要先通过索引找到需要的子组件,然后调用里面的值或则和函数

发表评论

表情:
评论列表 (有 0 条评论,104人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Vue父子组件

    Vue父子组件传值:有四种方式:props,ref,emit 和模板传递通信slot 通过props来传值: 静态传值就是直接通过props来传递 动态传值是通