vue值传递的几种方式

父子之间传递

父传子

  • 在父元素中绑定一个参数
1
<goods :index='index' :good ="item"></goods>
  • 在子元素中接受,使用props接收
1
2
3
4
5
props: {
good:{
type:Object
}
}

使用 this.good 可获取父组件传过来的值

子传父

  • 在子组件中触发
1
this.$emit('event1','要传递的值')
  • 在父元素监听事件 childData 事件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<Child @event1="change($event)"></Child>

import child from './child'
export default {
data() {
return {
newData: '这是父组件的数据'
}
},
methods: {
change(data) {
this.newData = data;
}
},
components: {child}
}

参考

兄弟间传值

子传父,父传子

vuex

  • 创建一个 store
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
}
})
  • 可以通过 store.state 来获取状态对象,以及通过 store.commit 方法触发状态变更:
1
2
3
store.commit('increment')

console.log(store.state.count) // -> 1
  • 为了在 Vue 组件中访问 this.$store property,你需要为 Vue 实例提供创建好的 store。Vuex 提供了一个从根组件向所有子组件,以 store 选项的方式“注入”该 store 的机制:
1
2
3
4
new Vue({
el: '#app',
store: store,
})
  • 现在我们可以从组件的方法提交一个变更:
1
2
3
4
5
6
methods: {
increment() {
this.$store.commit('increment')
console.log(this.$store.state.count)
}
}

vuex文档

eventBus

参考

  • 创建一个js文件,eventBus.js, 放在了src目录下
1
2
import Vue from 'vue'
export default new Vue()
  • 在brother1组件中,引入刚才的js
1
import '@/eventBus.js'
  • 然后在methods里边定义一个函数
1
2
3
4
5
methods:{
changesize(){
eventBus.$emit('add',this.arg)
}
}

button点击触发changesize函数,然后将arg传出去

  • 在brother2组件中也先引入eventBus.js,然后使用created生命周期函数
1
2
3
4
5
6
created(){
eventBus.$on('add',(message)=>{
//一些操作,message就是从top组件传过来的值
console.log(message)
})
}

query传参,或者params传参

1
2
3
4
5
6
7
8
9
this.$router.push({path: '/', query: {参数名: '参数值'}) 

this.$router.push({name: '/', params: {参数名: '参数值'})

<!-- 使用params时不能使用path -->

var a = this.$route.query.参数名

var b = this.$route.params.参数名

参考