• 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');
    

      

  • 相关阅读:
    linux 查看 服务 命令
    Java Swing中键盘事件的处理(转)
    VI常用命令及快捷键(转)
    Linux source用法(转)
    无线桥接 WDS 中继(转)
    在远程桌面连接中使用任务管理器(转)
    linux 运行 级别(转)
    linux 当前用户 命令 w who(转)
    vecket适合和不适合的10种人(转)
    在查找预编译头使用时跳过解决(转)
  • 原文地址:https://www.cnblogs.com/uimeigui/p/13384503.html
Copyright © 2020-2023  润新知