1.路由传值
a.在 main.js routes 中配置路由匹配规则
1 2 3 4 5 6
| routes: [ { path: '/xxx/:id', component: xxx } ]
|
b.在点击跳转的 router-link 标签中写上路径和参数
1
| <router-link :to="'/xxx/' + this.id"></router-link>
|
c.在跳转之后的页面,使用 $route.params 获取值
1 2 3 4 5
| export default { created () { console.log(this.$route.params.id) } }
|
2.父组件向子组件传值
a.父组件在子组件占位符上,以属性名=参数的形式写上要传递的值
1
| <subComp :fatherToSon:"this.value"></subComp>
|
b.子组件在 props 中写上子组件占位符的属性名
1 2 3
| export default { props: ['fatherToSon'] }
|
c.子组件使用 this.属性名 获取值
1 2 3 4 5 6
| export default { created () { console.log(this.fatherToSon) }, props: ['fatherToSon'] }
|
3.子组件向父组件传值
a.子组件中定义触发事件,写上自定义函数
1
| <button @click="sonToFather">子组件向父组件传值</button>
|
b.子组件在自定义函数中使用 $emit 触发父组件函数
1 2 3 4 5 6 7 8 9 10 11 12
| export default { data () { return { son: 222 } }, methods: { sonToFather () { this.$emit('getSonValue', this.son) } } }
|
c.父组件在子组件占位符上,使用 v-on 监听子组件使用 $emit 触发的函数
1
| <subComp @getSonValue="sonValue"></subCome>
|
d.父组件自定义函数中通过参数传递获取值
1 2 3 4 5 6 7
| export default { methods: { sonValue (value) { console.log(value) } } }
|
4.非父子组件传值
a.新建一个独立公共的vue实例
1 2
| import Vue from 'vue' export default new Vue()
|
b.发送方定义触发条件,写上自定义函数
1
| <button @click="notFatherAndSon">非父子组件传值</button>
|
c.发送方导入公共vue实例,并使用 $emit 触发父组件函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import bus from '../common/common.js' export default { data () { return { msg: '你好Vue' } }, methods: { notFatherAndSon () { bus.$emit('getNotFatherAndSon', this.msg) } } }
|
d.接收方导入公共vue实例,并使用 $on 监听发送发使用 $emit 触发的函数
1 2 3 4 5
| import bus from '../common/common.js' bus.$on('getNotFatherAndSon', (value) => { console.log(value) })
|
学习笔记,根据自己理解简单整理的,不对的地方望指正,非常感谢。