父组件向子组件传值
1 在子组件中写上props 在props中自定义名字
props: ['自定义名字']
2 在父组件中找到子组件标签 然后在子组件标签上 使用v-bind:自定义名字="父组件要发送的数据"
<子组件标签 :自定义名字="要发送的数据"></子组件标签>
3 在子组件中将自定义名字当做data使用
<元素标签>{{自定义名字}}</元素标签>
<div class="operate">
<Like :arr="lists"></Like> //子组件标签
</div>
export default {
props:['arr'] //子组件使用props接受
data() {
return {}
},
methods: {}
}
子组件向父组件传值
1 在子组件中 绑定自定义事件 使用this.$emit()发送数据
template: `
<button @click="自定义事件"></buttton>
`
methods: {
自定义事件() {
this.$emit("自定义事件名1",要发送的数据)
}
}
2 在父组件中 找到子组件标签 在子组件标签上 使用v-on:自定义事件名1="新的方法名"
<子组件标签 v-on:自定义事件名1="新的方法名"></子组件标签>
3 在父组件的methods里边 编写新的方法
methods: {
新的方法名(data) {
// data就是子组件传递过来数据
}
}
<template>
<button @click="send">发送</button> //这是子组件
</template>
export default {
data() {
return {
msg: '这是发送的数据',
}
},
methods: {
send() {
this.$emit("send", this.msg) //发送数据
},
}
}
<div id="app">
<child v-on:send="getData"></child> //在父组件找到子组件标签
</div>
export default {
data() {
return {}
},
methods: {
getData(data) {
console.log(11111, data) //在methods编写新的方法获取数据
}
}
}
非父子组件传值
$emit
发送数据
$on
监听数据
步骤:
1 创建公共实例化对象
const bus=new Vue()
2 在需要发送数据的组件中 使用bus.$emit("自定义名字",要传递数据)
methods: {
方法名() {
bus.$emit("自定义名字",要传递数据)
}
}
3 在需要接受数据的组件的生命周期created中 使用bus.$on监听数据
created() {
bus.$on("自定义名字",data=> {
// data就是传递过来的数据
})
}
import Vue from 'vue' //新建一个公共的实例化对象放到一个js文件中
const bus = new Vue()
export default bus
import bus from '../bus' //引入创建的js文件
<template>
<div class="top">
<button @click="send">发送</button>
</div>
</template>
export default {
//要发送数据的组件中
data() {
return {
msg: '要发送的数据',
}
},
methods: {
send() {
bus.$emit('send-msg', this.msg) //使用bus.$emit发送数据
}
}
}
import bus from '../bus' //引入j文件
export default {
data() {
return {}
},
created() {
bus.$on('send-msg', data => {
console.log(data); //在接受的组件中使用bus.$on接受
})
},
methods: {}
}
Vue2路由传值
路由组件传参
有两种方式:
1 斜杠传参(只能传递一个)
{
path: '/:自定义名字'
}
格式:
http://www.xxx.com/参数
获取:
this.$route.params.自定义名字
2 问号传参(能够传递多个)
{
path:'/路径'
}
格式:
http://www.xxx.com/路径?参数名1=参数值1&参数名2=参数值2
获取:
this.$route.query.参数名1 //参数值1
this.$route.query.参数名2 //参数值2