props:['自定义属性名']
来接收数据。<template> <!-- 父组件 --> <div> <Child :message="son1" v-if="typeCode == '0'"></Child> </div> </template> <script> // 引入子组件 import Child from "./subassembly/son.vue"; export default { data() { return { // typeCode: "0",//通过"0" "1"判断显示哪个页面;0:子组件1页面;1:子组件2页面 typeCode: "0", son1:"儿子" }; }, //一定要注册组件 components: { Child }, }; </script>
son.vue
<template> <!-- 子组件1 --> <h2>我是子组件1<br />接收父组件值:{{ message }}</h2> </template> <script> export default { data() { return {}; }, props: { // message用于接收 message: { type: String, //验证类型,也可以验证其他类型 default: "", //如果父组件传值,则用父组件的值渲染,反之使用默认值 }, }, mounted() { console.log(this.message); //父组件传递过来的数据 }, }; </script>
this.$emit('自定义事件名',要传递的数据)
发送父组件可以监听的数据,最后父组件监听子组件事件,调用事件并接收传递过来的数据。<template> <!-- 子组件1 --> <button @click="seedOnclick">我是子组件1</button> </template> <script> export default { data() { return { son1: "我是儿子", //子传父要传递的值 }; }, methods: { seedOnclick() { this.$emit("son", this.son1); //参数1:自定义事件;参数2:要传递的值 }, }, }; </script>
<template> <!-- 父组件 --> <div> <Child @seed="seedAccept" v-if="typeCode == '0'"></Child> </div> </template> <script> // 引入子组件 import Child from "./subassembly/son.vue"; export default { data() { return { //typeCode: "0", //通过"0" "1"判断显示哪个页面;0:子组件1页面;1:子组件2页面 typeCode: "0", }; }, //一定要注册组件 components: { Child, Electronic, }, methods: { seedAccept(data) { console.log(data, "子组件传给父组件的值"); } }, }; </script>
路由参数传递:
query
通过query传参 <router-link :to="{ path:'/home/message/detail', query:{ id: msg.id, title:msg.title } }"> 点击打开详细-{{msg.id}} </router-link>--> 简化请求路径 在index.js 中 通过name属性为路由 别名 path:'detail', name:'dt', component:Detail 使用时 通过name属性触发路由 注意 name 不能同名 <router-link :to="{ name:'dt',//使用name进行路由 query:{ id: msg.id, title:msg.title } }"> 点击打开详细-{{msg.id}} </router-link>--> <h2>消息编号:{{ $route.query.id }}</h2> <h2>消息标题:{{ $route.query.title }}</h2>
paramms
路由参数 params 参数 传递 path: 'detail/:id/:title', //使用占位符 声明 接收 name: 'dt', component: Detail, <router-link :to="{ name:'dt', params:{ id: msg.id, title:msg.title } }"> 点击打开详细-{{msg.id}} </router-link> 获取 <h2>消息编号:{{ $route.params.id }}</h2> <h2>消息标题:{{ $route.params.title }}</h2>
props
props 参数的传递 index.js props:['',''] props:true 将params的参数 转换为props格式 props($route) { return{ id:$route.params.id, title:$route.params.title } } 在目标组件中 声明属性 props: ['id', 'title']