一、Vue 路由 —> 父组件 —>子组件的参数传值
序言
笔者遇到了一个比较特殊的设计要求,从 Vue 路由传递某个参数给某个组件,然后在使用这个父组件将这个参数传递给子组件,看似挺复杂的,其实实现后,还是挺简单的。
可以说下方的参考链接好坏掺杂,本文是笔者提取了参考链接内的精华部分所写。
实现方法
- Vue 路由的配置文件:参数从路由这里开始传递
testindex: '0'
const router = new VueRouter({
mode: 'history',
base: __dirname,
routes: [{
path: '/test',
component: testfather,
props:{ testindex: '0'}
},
]
});
- 父组件配置:父组件接收到路由传递的参数值
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>
- 子组件配置:子组件接收到了父组件发送的消息,
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
参考链接
二、父组件触发子组件的函数
参考链接: