Vue通信、传值的多种方式,详解

转自:https://blog.csdn.net/qq_35430000/article/details/79291287

一、通过路由带参数进行传值

①两个组件 A和B,A组件通过query把orderId传递给B组件(触发事件可以是点击事件、钩子函数等)

this.$router.push({ path: '/conponentsB', query: { orderId: 123 } }) // 跳转到B

②在B组件中获取A组件传递过来的参数

this.$route.query.orderId

二、通过设置 Session Storage缓存的形式进行传递

①两个组件A和B,在A组件中设置缓存orderData

  1.  
    const orderData = { 'orderId': 123, 'price': 88 }
  2.  
     
  3.  
    sessionStorage.setItem('缓存名称', JSON.stringify(orderData))

②B组件就可以获取在A中设置的缓存了

const dataB = JSON.parse(sessionStorage.getItem('缓存名称'))

此时 dataB 就是数据 orderData

朋友们可以百度下 Session Storage(程序退出销毁) 和 Local Storage(长期保存) 的区别。

三、父子组件之间的传值

(一)父组件往子组件传值props

①定义父组件,父组件传递 number这个数值给子组件,如果传递的参数很多,推荐使用json数组{}的形式

②定义子组件,子组件通过 props方法获取父组件传递过来的值。props中可以定义能接收的数据类型,如果不符合会报错。

③假如接收的参数 是动态的,比如 input输入的内容 v-model的形式

注意:传递的参数名称不识别驼峰命名,推荐使用横杠-命名

④父子组件传值,数据是异步请求,有可能数据渲染时报错

原因:异步请求时,数据还没有获取到但是此时已经渲染节点了

解决方案:可以在 父组件需要传递数据的节点加上  v-if = false,异步请求获取数据后,v-if = true

(二)、子组件往父组件传值,通过emit事件

四、不同组件之间传值,通过eventBus(小项目少页面用eventBus,大项目多页面使用 vuex)

①定义一个新的vue实例专门用于传递数据,并导出

②定义传递的方法名和传输内容,点击事件或钩子函数触发eventBus.emit事件

③接收传递过来的数据

注意:enentBus是一个另一个新的Vue实例,区分两个this所代表得vue实例

五、vuex进行传值

为什么使用vuex?

vuex主要是是做数据交互,父子组件传值可以很容易办到,但是兄弟组件间传值(兄弟组件下又有父子组件),或者大型spa单页面框架项目,页面多并且一层嵌套一层的传值,异常麻烦,用vuex来维护共有的状态或数据会显得得心应手。

需求:两个组件A和B,vuex维护的公共数据是 餐馆的名称 resturantName,默认餐馆名称是 飞歌餐馆,那么现在A和B页面显示的就是飞歌餐馆。如果A修改餐馆名称 为 A餐馆,则B页面显示的将会是 A餐馆,反之B修改同理。这就是vuex维护公共状态或数据的魅力,在一个地方修改了数据,在这个项目的其他页面都会变成这个数据。

         

①使用 vue-cli脚手架工具创建一个工程项目,工程目录,创建组件A和组件B路由如下:

路由如下:

  1.  
    import Vue from 'vue'
  2.  
    import Router from 'vue-router'
  3.  
    import componentsA from '@/components/componentsA'
  4.  
    import componentsB from '@/components/componentsB'
  5.  
     
  6.  
    Vue.use(Router)
  7.  
     
  8.  
    export default new Router({
  9.  
    mode: 'history',
  10.  
    routes: [
  11.  
    {
  12.  
    path: '/',
  13.  
    name: 'componentsA',
  14.  
    component: componentsA
  15.  
    },
  16.  
    {
  17.  
    path: '/componentsA',
  18.  
    name: 'componentsA',
  19.  
    component: componentsA
  20.  
    },
  21.  
    {
  22.  
    path: '/componentsB',
  23.  
    name: 'componentsB',
  24.  
    component: componentsB
  25.  
    }
  26.  
    ]
  27.  
    })

app.vue

  1.  
    <template>
  2.  
    <div id="app">
  3.  
    <router-view/>
  4.  
    </div>
  5.  
    </template>
  6.  
     
  7.  
    <script>
  8.  
    export default {
  9.  
    name: 'App'
  10.  
    }
  11.  
    </script>
  12.  
     
  13.  
    <style>
  14.  
    #app {
  15.  
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
  16.  
    -webkit-font-smoothing: antialiased;
  17.  
    -moz-osx-font-smoothing: grayscale;
  18.  
    text-align: center;
  19.  
    color: #2c3e50;
  20.  
    margin-top: 60px;
  21.  
    }
  22.  
    </style>

②开始使用vuex,新建一个 sotre文件夹,分开维护 actions mutations getters

②在store/index.js文件中新建vuex 的store实例

*as的意思是 导入这个文件里面的所有内容,就不用一个个实例来导入了。

  1.  
    import Vue from 'vue'
  2.  
    import Vuex from 'vuex'
  3.  
    import * as getters from './getters' // 导入响应的模块,*相当于引入了这个组件下所有导出的事例
  4.  
    import * as actions from './actions'
  5.  
    import * as mutations from './mutations'
  6.  
     
  7.  
    Vue.use(Vuex)
  8.  
    // 首先声明一个需要全局维护的状态 state,比如 我这里举例的resturantName
  9.  
    const state = {
  10.  
    resturantName: '飞歌餐馆' // 默认值
  11.  
    // id: xxx 如果还有全局状态也可以在这里添加
  12.  
    // name:xxx
  13.  
    }
  14.  
     
  15.  
    // 注册上面引入的各大模块
  16.  
    const store = new Vuex.Store({
  17.  
    state, // 共同维护的一个状态,state里面可以是很多个全局状态
  18.  
    getters, // 获取数据并渲染
  19.  
    actions, // 数据的异步操作
  20.  
    mutations // 处理数据的唯一途径,state的改变或赋值只能在这里
  21.  
    })
  22.  
     
  23.  
    export default store // 导出store并在 main.js中引用注册。

③actions

  1.  
    // 给action注册事件处理函数。当这个函数被触发时候,将状态提交到mutations中处理
  2.  
    export function modifyAName({commit}, name) { // commit 提交;name即为点击后传递过来的参数,此时是 'A餐馆'
  3.  
    return commit ('modifyAName', name)
  4.  
    }
  5.  
    export function modifyBName({commit}, name) {
  6.  
    return commit ('modifyBName', name)
  7.  
    }
  8.  
     
  9.  
    // ES6精简写法
  10.  
    // export const modifyAName = ({commit},name) => commit('modifyAName', name)

④mutations

  1.  
    // 提交 mutations是更改Vuex状态的唯一合法方法
  2.  
    export const modifyAName = (state, name) => { // A组件点击更改餐馆名称为 A餐馆
  3.  
    state.resturantName = name // 把方法传递过来的参数,赋值给state中的resturantName
  4.  
    }
  5.  
    export const modifyBName = (state, name) => { // B组件点击更改餐馆名称为 B餐馆
  6.  
    state.resturantName = name
  7.  
    }

⑤getters

  1.  
    // 获取最终的状态信息
  2.  
    export const resturantName = state => state.resturantName

⑥在main.js中导入 store实例

  1.  
    // The Vue build version to load with the `import` command
  2.  
    // (runtime-only or standalone) has been set in webpack.base.conf with an alias.
  3.  
    import Vue from 'vue'
  4.  
    import App from './App'
  5.  
    import router from './router'
  6.  
    import store from './store'
  7.  
     
  8.  
    Vue.config.productionTip = false
  9.  
     
  10.  
    /* eslint-disable no-new */
  11.  
    new Vue({
  12.  
    el: '#app',
  13.  
    router,
  14.  
    store, // 这样就能全局使用vuex了
  15.  
    components: { App },
  16.  
    template: '<App/>'
  17.  
    })

④在组件A中,定义点击事件,点击 修改 餐馆的名称,并把餐馆的名称在事件中用参数进行传递。

...mapactions 和 ...mapgetters都是vuex提供的语法糖,在底层已经封装好了,拿来就能用,简化了很多操作。

其中...mapActions(['clickAFn']) 相当于this.$store.dispatch('clickAFn',{参数}),mapActions中只需要指定方法名即可,参数省略。

...mapGetters(['resturantName'])相当于this.$store.getters.resturantName

  1.  
    <template>
  2.  
    <div class="componentsA">
  3.  
    <P class="title">组件A</P>
  4.  
    <P class="titleName">餐馆名称:{{resturantName}}</P>
  5.  
    <div>
  6.  
    <!-- 点击修改 为 A 餐馆 -->
  7.  
    <button class="btn" @click="modifyAName('A餐馆')">修改为A餐馆</button>
  8.  
    </div>
  9.  
    <div class="marTop">
  10.  
    <button class="btn" @click="trunToB">跳转到B页面</button>
  11.  
    </div>
  12.  
    </div>
  13.  
    </template>
  14.  
     
  15.  
    <script>
  16.  
    import {mapActions, mapGetters} from 'vuex'
  17.  
    export default {
  18.  
    name: 'A',
  19.  
    data () {
  20.  
    return {
  21.  
    }
  22.  
    },
  23.  
    methods:{
  24.  
    ...mapActions( // 语法糖
  25.  
    ['modifyAName'] // 相当于this.$store.dispatch('modifyName'),提交这个方法
  26.  
    ),
  27.  
    trunToB () {
  28.  
    this.$router.push({path: '/componentsB'}) // 路由跳转到B
  29.  
    }
  30.  
    },
  31.  
    computed: {
  32.  
    ...mapGetters(['resturantName']) // 动态计算属性,相当于this.$store.getters.resturantName
  33.  
    }
  34.  
    }
  35.  
    </script>
  36.  
     
  37.  
    <!-- Add "scoped" attribute to limit CSS to this component only -->
  38.  
    <style scoped>
  39.  
    .title,.titleName{
  40.  
    color: blue;
  41.  
    font-size: 20px;
  42.  
    }
  43.  
    .btn{
  44.  
    width: 160px;
  45.  
    height: 40px;
  46.  
    background-color: blue;
  47.  
    border: none;
  48.  
    outline: none;
  49.  
    color: #ffffff;
  50.  
    border-radius: 4px;
  51.  
    }
  52.  
    .marTop{
  53.  
    margin-top: 20px;
  54.  
    }
  55.  
    </style>

B组件同理

  1.  
    <template>
  2.  
    <div class="componentsB">
  3.  
    <P class="title">组件B</P>
  4.  
    <P class="titleName">餐馆名称:{{resturantName}}</P>
  5.  
    <div>
  6.  
    <!-- 点击修改 为 B 餐馆 -->
  7.  
    <button class="btn" @click="modifyBName('B餐馆')">修改为B餐馆</button>
  8.  
    </div>
  9.  
    <div class="marTop">
  10.  
    <button class="btn" @click="trunToA">跳转到A页面</button>
  11.  
    </div>
  12.  
    </div>
  13.  
    </template>
  14.  
     
  15.  
    <script>
  16.  
    import {mapActions, mapGetters} from 'vuex'
  17.  
    export default {
  18.  
    name: 'B',
  19.  
    data () {
  20.  
    return {
  21.  
    }
  22.  
    },
  23.  
    methods:{
  24.  
    ...mapActions( // 语法糖
  25.  
    ['modifyBName'] // 相当于this.$store.dispatch('modifyName'),提交这个方法
  26.  
    ),
  27.  
    trunToA () {
  28.  
    this.$router.push({path: '/componentsA'}) // 路由跳转到A
  29.  
    }
  30.  
    },
  31.  
    computed: {
  32.  
    ...mapGetters(['resturantName']) // 动态计算属性,相当于this.$store.getters.resturantName
  33.  
    }
  34.  
    }
  35.  
    </script>
  36.  
     
  37.  
    <!-- Add "scoped" attribute to limit CSS to this component only -->
  38.  
    <style scoped>
  39.  
    .title,.titleName{
  40.  
    color: red;
  41.  
    font-size: 20px;
  42.  
    }
  43.  
    .btn{
  44.  
    width: 160px;
  45.  
    height: 40px;
  46.  
    background-color: red;
  47.  
    border: none;
  48.  
    outline: none;
  49.  
    color: #ffffff;
  50.  
    border-radius: 4px;
  51.  
    }
  52.  
    .marTop{
  53.  
    margin-top: 20px;
  54.  
    }
  55.  
    </style>

最后:本文完全手打,如需转载请注明出处,谢谢,如果不明白的地方欢迎给我留言哦。

github项目仓库地址:https://github.com/byla678/vuexdemo.git

Vue通信、传值的多种方式,详解的更多相关文章

  1. Vue通信、传值的多种方式,详解(都是干货)

    Vue通信.传值的多种方式,详解(都是干货) 可参考博客: https://blog.csdn.net/qq_35430000/article/details/79291287

  2. VUE SpringCloud 跨域资源共享 CORS 详解

    VUE  SpringCloud 跨域资源共享 CORS 详解 作者:  张艳涛 日期: 2020年7月28日 本篇文章主要参考:阮一峰的网络日志 » 首页 » 档案 --跨域资源共享 CORS 详解 ...

  3. Windows主机里利用VMware安装Linux(CentOS)虚拟机,Host-only连接上网方式详解

    关于Host-only指的是主机与虚拟机之间的互联,因此虚拟机是不能连网的,若需要连网则需要使用NAT模式: Host-only模式实现联网得考虑如下配置过程: 附:VMware虚拟机三种网络模式(B ...

  4. 串口通信-MSComm控件使用详解

    串口通信-MSComm控件使用详解 2012年11月13日 09:35:45 他山之石可以攻玉 阅读数:37952更多 个人分类: 控件编程Delphi编程   MSComm 控件通过串行端口传输和接 ...

  5. vuex的使用及持久化state的方式详解

    vuex的使用及持久化state的方式详解 转载  更新时间:2018年01月23日 09:09:37   作者:baby格鲁特    我要评论 这篇文章主要介绍了vuex的使用及持久化state的方 ...

  6. Linux/centos/redhat下各种压缩解压缩方式详解

    1.zip命令 zip -r myfile.zip ./* 将当前目录下的所有文件和文件夹全部压缩成myfile.zip文件,-r表示递归压缩子目录下所有文件. 2.unzip unzip -o -d ...

  7. Spring事务Transaction配置的五种注入方式详解

    Spring事务Transaction配置的五种注入方式详解 前段时间对Spring的事务配置做了比较深入的研究,在此之间对Spring的事务配置虽说也配置过,但是一直没有一个清楚的认识.通过这次的学 ...

  8. Dubbo配置方式详解

    Dubbo 是一个分布式服务框架,致力于提供高性能和透明化的 RPC 远程服务调用方案,是阿里巴巴 SOA 服务化治理方案的核心框架,每天为 2,000+ 个服务提供 3,000,000,000+ 次 ...

  9. JSON创建键值对(key是中文或者数字)方式详解

    JSON创建键值对(key是中文或者数字)方式详解 先准备好一个空的json对象 var obj = {}; 1. 最原始的方法 obj.name = 'zhangsan'; //这种方式很简单的添加 ...

随机推荐

  1. 用grep在子目录中指定的文件类型中查找(转载)

    转自:http://www.ai7.org/wp/html/653.html grep -r abcd *.py 这样的命令得不到你期待的结果,而 grep -r abcd * 这样得到的结果又太多, ...

  2. E20180412-hm

    overflow  vt. 溢出,淹没; 挤满,充满; 洋溢; 资源过剩;   n. 泛滥,溢出物; 溢流管; 充溢,过多; 超出额;   vi. 泛滥,溢出; 充溢;

  3. 51nod 1225:余数之和

    传送门 题意 略 分析 \(\sum_i^n(n\%i)=\sum_i^n(n-i*n/i)=n^2-\sum_i^ni*n/i\) \(=\sum r\sum_i^ni[n/i==r]\) 可以证明 ...

  4. POJ1050【DP】

    题意: 求一个最大子矩阵和. 思路: 枚举行区间,然后求一个最大子序列和. 贴一发挫code- #include <iostream> #include <cstdio> #i ...

  5. python __builtins__ dict类 (17)

    17.'dict', 用于创建一个字典. class dict(object) | dict() -> new empty dictionary # 空字典 | dict(mapping) -& ...

  6. bzoj 2780: [Spoj]8093 Sevenk Love Oimaster【广义SAM】

    AC自动机比较简单,把询问串做成AC自动机然后模板串边跑变更新即可 SAM是把模板串做成广义SAM,然后每个节点存有几个模板串经过,具体方法是每次更新暴力向上跳直到有时间戳我不会证为什么时间复杂度是对 ...

  7. POJ 1151 Atlantis(扫描线)

    题目原链接:http://poj.org/problem?id=1151 题目中文翻译: POJ 1151 Atlantis Time Limit: 1000MS   Memory Limit: 10 ...

  8. windows 异步通知I/O模型与重叠I/O模型

    一.异步IO模型(asynchronous IO) (1)什么是异步I/O 异步I/O(asynchronous I/O)由POSIX规范定义.演变成当前POSIX规范的各种早起标准所定义的实时函数中 ...

  9. nginx使用autoindex

    有时候一个nginx服务就是为了用来下载文件的,网上很多下载服务都是这样的 这个很简单 在http段加上以下参数,重启nginx就行. autoindex on; autoindex_exact_si ...

  10. Smart 组件 vs Dumb 组件

    大家已经知道,只会接受 props 并且渲染确定结果的组件我们把它叫做 Dumb 组件,这种组件只关心一件事情 —— 根据 props 进行渲染. Dumb 组件最好不要依赖除了 React.js 和 ...