vue组件传值的几种方式

1、bus总线

//定义bus插件

//在util文件夹下定义bus.js

import Vue from 'vue';

let install = (vue) => {
    vue.prototype.bus = new Vue();
}
export default install;

1.1、用到bus总线的地方,兄弟组件传值(父子组件也可以使用bus总线,但他使用自身的this.$emit his.$on,更方便,相当于bus总线的变种)

//在main.js中引入bus,方便在全局使用:

 1.2、接下来就可以在组件A和组件B中使用

//组件A接受组件B传递来的数据
  created() {
    this.bus.$on("hello", (data) => {
        console.log(data);
      });
  },

//组件B传递

<template>
    <button @click="handle">传递参数</button>
</template>
<script>
export default{
    methods:{
        handle(){
            this.bus.$emit("hello", { obj: 123 });
        }
    }
}
</script>        

  

2、路由传参:

1、命名路由传参
this.$router.push({ name: 'user', params: { user: 'nickname' }});
//页面接受
this.$route.params
2、查询参数传参
this.$router.push({path: '/user', query: {user: "nickname"}});
//页面接受
this.$route.query

3、父子组件传参

//子组件
this.$emit("update",123);
//父组件触发
<children @update="update" />     //children代表子组件
export default{
    methods:{
       update(data){
            console.log(data);
        }
    }
}
    

4、vuex全局使用参数

//新建store.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
  }
})
//main.js中引入,就可以全局使用state
import store from './store'
new Vue({
  store,
  render: h => h(App)
}).$mount('#app');

  

原文地址:https://www.cnblogs.com/uimeigui/p/13384503.html