vue组件间传值方式

前言:vue组件传值在开发中遇到的频率很高,以防遗忘,故写一篇博客记录一下。

1、prop父传子
父组件:

<template>
  <div id="father">
	<Children :byData="fatherByChildren"/>   <!--:’为‘v-bind’的简写,这里使用‘v-bind’,使用传的是fatherByChildren这个对象,不使用传的是fatherByChildren这个字符串 -->
  </div>
</template>

<script>
import Children from '../components/Children.vue'  // 引入Children组件
export default {
  name: 'father',
  data () {
    return {
      fatherByChildren:"这是Father传给Children的值"
    }
  },
  // ...其它代码
}
</script>

子组件(props接收参数):

<script>
export default {
  name: 'children',
  props: {
    byData: String    
  },
  // ...其它代码
}
</script>

2、$emit()子传父
父组件:

<template>
  <div id="father">
	<Children @childrenByFather="childrenByFather"/>  
  </div>
</template>

<script>
import Children from '../components/Children.vue'  // 引入Children组件
export default {
  name: 'father',
  data () {
    return {
   		
    }
  },
  methods: {
  	childrenByFather(val) {
  		console.log(val)  // 输出子组件传来的值:‘这是Father传给Children的值’
  	}
  }
  // ...其它代码
}
</script>

子组件:

<template>
  <div id="children">
	<button @click="goClick">点击传值</button>
  </div>
</template>

<script>
export default {
  name: 'children',
  data () {
    return {
      childrenByFather:"这是Father传给Children的值"
    }
  },
  methods: {
  	goClick() {
		this.$emit('childrenByFather', this.childrenByFather)   // 触发父组件中childrenByFather事件,并将childrenByFather对象传过去
	}
  }
  // ...其它代码
}
</script>

3、非父子组件传值:
非父子之间传值,可以采用发布订阅模式,这种模式在 Vue 中被称为总线机制,或者叫做Bus / 发布订阅模式 / 观察者模式
在main.js中挂载bus属性,所有的子组件都能调用:

Vue.prototype.bus = new Vue()           //挂载 bus 属性

组件A中(传):

this.bus.$emit('change',this.message)   // 发布
// this.message为要传的值

组件B中(收):

this.bus.$on('change',(msg)=>{          //订阅
	this.message= msg    // msg为组件传来的值
})

4、vuex状态管理:
store.js中:

export default new Vuex.store({
    state: {   // 写入数据,类似组件中data
        name: '天天'
    },
    actions: {   // 异步更改(接口请求)
        changeName ({commit}, modifyName) {         
            commit('changeName', modifyName)      //通过 commit 调用 mutations 中的changeName方法
        }
    },
    mutations: {  // 同步更改
        changeName (state, modifyName) {
            state.name = modifyName
        }
    }
})

组件中使用 state 中的 name:

this.$store.state.name

组件中修改 state 中的 name 的值:
①没有任何异步操作,直接调用 mutations 中的 changeName 方法:

this.$store.commit('changeName', modifyName)        //派发一个名字叫 changeName 的 mutation,并把 modifyName传递过去

②有异步操作,必须调用 Actions 做转发:

this.$store.dispatch('changeName', modifyName)        //派发一个名字叫 changeName 的 Actions,并把 modifyName 传过去
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值