Vue - Vue 路由 - 组件通信 —> 父组件 —>子组件的参数传值 、父组件触发子组件的函数

一、Vue 路由 —> 父组件 —>子组件的参数传值

序言

笔者遇到了一个比较特殊的设计要求,从 Vue 路由传递某个参数给某个组件,然后在使用这个父组件将这个参数传递给子组件,看似挺复杂的,其实实现后,还是挺简单的。

可以说下方的参考链接好坏掺杂,本文是笔者提取了参考链接内的精华部分所写。

实现方法

  1. Vue 路由的配置文件:参数从路由这里开始传递 testindex: '0'
const router = new VueRouter({
  mode: 'history',
  base: __dirname,
  routes: [{
      path: '/test',
      component: testfather,
      props:{ testindex: '0'} 
  },
  ]
});
  1. 父组件配置:父组件接收到路由传递的参数值 testindex: '0',然后再发送给子组件的参数 getindex,注意冒号 : 是通信接收对象的指定操作
<template>
<testchild :getindex="testindex">
 </testchild >
</template>
<script>
import testchild from "../components/testchild";

export default {
  name: 'testfather',
  components: { testchild },
  props: ['testindex'],
  data() {
    return {
    }
  },
}
</script>
  1. 子组件配置:子组件接收到了父组件发送的消息,type 限定参数类型为字符串类型,default默认值是 ‘-1’
<template>
<div>
<p>  ---------------  测试 ---------------  </p>
<p> 这是传递的参数使用方法作为中间件 {{ curractive }} </p>
<p>  这是传递的参数 {{ getindex }} 虽然可以,但不推荐这样使用</p>
</div>
</template>
<script>

export default {
  name: 'testchild',
  props: {
    getindex: {
      type: String,
      default: '-1'
    },
  },
  data() {
    return {
    	testdata: ''
    }
  },
   computed:{
    curractive:function (){
      this.testdata = this.getindex;
      console.log("用这个computed 的方法也是可以的,效果一样", this.testdata)
      return this.testdata
    }
  },
}
</script>

个人理解

props:该参数可以说 数组类型,比如[a, b, c ] ,也可以说对象类型,比如{a:{ type: String, default: '' } }的,但如果是在使用对象类型的数据格式限制时,请注意传递的参数格式类型是否对的上。

最后,最好是不要直接使用 props 的参数,最好是赋予给另外的参数,该参数是被父组件所引用的,所以如果该 props 内的参数在子组件内有所变化,父组件也会被跟着变化,而且还有可能会报错,如上所示,子组件内的 props 的参数 getindex ,笔者是重新赋予给其他的参数 testdata


参考链接

1. vue中 关于$emit的用法

2. Vue中父子组件如何传值

3. ⑩ Vue父组件向子组件传值

4. Vue路由组件传参

5. Vue中父组件向子组件传递数据的几种方法

6. 超详细的Vue渲染原理讲解


二、父组件触发子组件的函数

参考链接:

vue父组件触发子组件事件

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值