vue通信方式

一、创建项目

1、打开命令运行框
2、输入vue create tongxin
3、选择 Manually select features,按回车
4、选择Babel、Router、Vuex、CSS Pre-processors,按回车
5、按Y
6、看个人兴趣,一般Sass/SCSS (with dart-sass)或less
7、选In dedicated config files
8、按N

二、常用通信方式

1、父传子(使用props)

(1)首先将.vue文件中没用的信息删除

(2)在App.vue引入Home.vue组件

<template>
  <div class="app">
    <home :list="list"/>
  </div>
</template>
<script>
import Home from "@/views/Home";
export default {
  components: {Home},
  data(){
    return{
      list:[
        {
          id:1,
          title: "通信1"
        },
        {
          id:2,
          title: "通信2"
        }
      ]
    }
  }
}
</script>
<style lang="scss">
</style>

(3)在home.vue中通过props拿到App.vue中信息

<template>
  <div class="home">
    <ul>
      <li v-for="(item,i) in list" :key="i">
        {{item.title}}
      </li>
    </ul>
  </div>
</template>
<script>
export default {
  props:{
    list: "",
  }
}
</script>
<style lang="scss">
</style>

(4)结果展示

在这里插入图片描述

2、子传父(使用$emit)

(1)编写About.vue组件

<template>
  <div class="home">
    <input type="text" v-model="title">
    <button @click="add">添加</button>
  </div>
</template>
<script>
export default {
  data(){
    return{
      title: "",
    }
  },
  methods:{
    add(){
      // 触发一个add事件,将输入的标题值带出去
      this.$emit("add",this.title)
    }
  }
}
</script>
<style lang="scss">
</style>

(2)在App.vue引入About.vue组件

<template>
  <div class="app">
<!--    监听add事件-->
    <about @add="add"/>
    <home :list="list"/>
  </div>
</template>
<script>
import About from "@/views/About";
import Home from "@/views/Home";
export default {
  components: {Home, About},
  data(){
    return{
      list:[
        {
          id:1,
          title: "通信1"
        },
        {
          id:2,
          title: "通信2"
        }
      ]
    }
  },
  methods:{
    add(title){
      this.list.push({
        id: Math.random(),
        title
      })
    }
  }
}
</script>
<style lang="scss">
</style>

(3)结果展示

在这里插入图片描述

3、兄弟之间(使用vuex)

1、vuex是什么

Vuex是实现组件全局状态(数据),管理的一种机制,可以方便的实现组件之间数据的共享。

2、vuex统一状态管理的好处

1、能够在vuex中集中管理共享的数据,已于开发和后期维护。
2、能够高效的实现组件之间的数据共享,提高开发效率。
3、存储在vuex中数据都在响应式的,能够实时保持数据与页面的同步。

3、什么样的数据适合存储在vuex中

一般情况下,只有组件之间共享的数据,才有必要存储到vuex中,对于组件中的私有数据,依旧存储在组件自身的data中即可。

4、vuex的使用

(1)安装vuex依赖
npm install vuex --save
(2)导入vuex包及创建store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  //state中存放的就是全局共享的数据
  state: {
    count: 0
  },
  mutations: {
  },
  actions: {
  },
  modules: {
  }
})
(3)将store对象挂在到vue实例(main.js)中
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
Vue.config.productionTip = false
new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
(4)创建components/Addition.vue
<template>
  <div>
    <h3>当前最新的count值为:</h3>
    <button>-1</button>
  </div>
</template>
<script>
export default {
name: "Addition",
  data(){
    return{
    }
  }
}
</script>
<style scoped>
</style>

(5)创建components/Subtraction.vue
<template>
  <div>
    <h3>当前最新的count值为:</h3>
    <button>-1</button>
  </div>
</template>
<script>
export default {
  name: "Subtraction",
  data(){
    return{
    }
  }
}
</script>
<style scoped>
</style>
(5)在App.vue中引入
<template>
  <div class="app">
<!--    监听add事件-->
    <about @add="add"/>
    <home :list="list"/>
    <p>-------------------</p>
    <Addition/>
    <p>===================</p>
    <Subtraction/>
  </div>
</template>
<script>
import About from "@/views/About";
import Home from "@/views/Home";
import Addition from "@/components/Addition";
import Subtraction from "@/components/Subtraction";
export default {
  components: {
    Home,
    About,
    Addition,
    Subtraction,
  },
  data(){
    return{
      list:[
        {
          id:1,
          title: "通信1"
        },
        {
          id:2,
          title: "通信2"
        }
      ]
    }
  },
  methods:{
    add(title){
      this.list.push({
        id: Math.random(),
        title
      })
    }
  }
}
</script>
<style lang="scss">
</style>

5、vuex核心概念

(1)State
State提供唯一的公共数据源,所有共享的数据都要统一放到Store的State中进行存储。

// store/index.js
export default new Vuex.Store({
  //state中存放的就是全局共享的数据
  state: {
    count: 0
  },
})

//组件访问方式一(详情参考下方Addition.vue)
this.$store.state.全局数据名称
//组件访问方式二(详情参考下方Subtraction.vue)
(1)从vuex中按需导入mapState函数
import { mapState } from 'vuex'
通过刚才导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性。
(2)将全局数据,映射为当前组件的计算属性
computed:{
  ...mapState(['count'])
}

当前的components/Addition.vue

<template>
  <div>
    <h3>当前最新的count值为:{{$store.state.count}}</h3>
    <button>-1</button>
  </div>
</template>
<script>
export default {
name: "Addition",
  data(){
    return{
    }
  }
}
</script>
<style scoped>
</style>

当前的components/Subtraction.vue

<template>
  <div>
    <h3>当前最新的count值为:{{count}}</h3>
    <button>-1</button>
  </div>
</template>
<script>
import { mapState } from 'vuex'
export default {
  name: "Subtraction",
  data(){
    return{
    }
  },
  computed:{
    ...mapState(['count'])
  }
}
</script>
<style scoped>
</style>
(2)Mutation
Mutation用于变更Store中的数据
(1)只能通过mutation变更Store数据,不可以直接操作Store中的数据。
(2)通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化。

// store/index.js
export default new Vuex.Store({
  //state中存放的就是全局共享的数据
  state: {
    count: 0
  },
  mutations: {
    add(state){
      //不要再mutations中执行异步操作
      // setTimeout(()=>{
      //   state.count++
      // },1000)
      state.count++
    },
    addN(state,step){
      state.count += step
    },
    sub(state){
      state.count--
    },
    subN(state,step){
      state.count -= step
    },
  },
})

// 触发mutation的第一种方法
methods:{
  btnHandel1(){
     this.$store.commit('add')
  },
  btnHandelN(){
     this.$store.commit('add',3)
  }
}

// 触发mutation的第二种方法
(1)从vuex中按需导入mapMutations函数
import { mapMutations } from 'vuex'
(2)将指定的mutations函数,映射为当前组件的methods方法
methods:{
  ...mapMutations(['add','addN'])
}

当前的components/Addition.vue

<template>
  <div>
    <h3>当前最新的count值为:{{$store.state.count}}</h3>
    <button @click="btnHandler1">+1</button><br>
    <button @click="btnHandlerN">+N</button>
  </div>
</template>
<script>
export default {
name: "Addition",
  data(){
    return{
    }
  },
  methods:{
    btnHandler1(){
      this.$store.commit('add')
    },
    btnHandlerN(){
      this.$store.commit('addN',3)
    }
  }
}
</script>
<style scoped>
</style>

当前的components/Subtraction.vue

<template>
  <div>
    <h3>当前最新的count值为:{{count}}</h3>
    <button @click="btnHandler1">-1</button><br>
    <button @click="btnHandlerN">-N</button>
  </div>
</template>
<script>
import { mapState,mapMutations } from 'vuex'
export default {
  name: "Subtraction",
  data(){
    return{
    }
  },
  computed:{
    ...mapState(['count'])
  },
  methods:{
    ...mapMutations(['sub','subN']),
    btnHandler1(){
      this.sub()
    },
    btnHandlerN(){
      this.subN(3)
    },
  }
}
</script>
<style scoped>
</style>
(3)Action
Action用于处理异步任务
//定义Action
export default new Vuex.Store({
  //state中存放的就是全局共享的数据
  state: {
    count: 0
  },
  mutations: {
    add(state){
      state.count++
    },
  },
  actions: {
    addAsync(context){
      setTimeout(() =>{
        context.commit('add')
      },1000)
    }
  },
})

//触发Action第一种方式
methods:{
  handle(){
   this.$store.dispatch('addAsync')
  }
}

//触发actions异步任务时携带参数:
export default new Vuex.Store({
  //state中存放的就是全局共享的数据
  state: {
    count: 0
  },
  //只有mutations中定义的函数,才有权力修改state中的数据
  mutations: {
    addN(state,step){
      state.count += step
    },
  },
  actions: {
    addAsyncN(context,step){
      setTimeout(() =>{
        //在action中不能直接修改state中的数据
        //必须通过context.commit('add')来触发某个mutation才行
        context.commit('addN',step)
      },1000)
    }
  },
})

//触发Action
methods:{
  //异步的让count自增N
  btnHandler4(){
    //这里的dispatch函数,专门用来触发actions时携带参数
    this.$store.dispatch('addAsyncN',5)
  }
}

//触发actions的第二种方法
(1)从vuex中按需导入mapActions函数
import { mapActions } from 'vuex'
(2)将指定的actions函数,映射为当前组件的methods函数。
methods:{
  ...mapActions(['addAsync','addAsyncN'])
}

当前的components/Addition.vue

<template>
  <div>
    <h3>当前最新的count值为:{{$store.state.count}}</h3>
    <button @click="btnHandler1">+1</button><br>
    <button @click="btnHandlerN">+N</button><br>
    <button @click="btnHandler3">+1 Async</button><br>
    <button @click="btnHandler4">+N Async</button>
  </div>
</template>
<script>
export default {
name: "Addition",
  data(){
    return{
    }
  },
  methods:{
    btnHandler1(){
      this.$store.commit('add')
    },
    btnHandlerN(){
      //commit的作用,就是调用某个mutation函数
      this.$store.commit('addN',3)
    },
    //异步的让count自增1
    btnHandler3(){
      //这里的dispatch函数,专门用来触发action
      this.$store.dispatch('addAsync')
    },
    //异步的让count自增N
    btnHandler4(){
      //这里的dispatch函数,专门用来触发actions时携带参数
      this.$store.dispatch('addAsyncN',5)
    }
  }
}
</script>
<style scoped>
</style>

当前的components/Subtraction.vue

<template>
  <div>
    <h3>当前最新的count值为:{{count}}</h3>
    <button @click="btnHandler1">-1</button><br>
    <button @click="btnHandlerN">-N</button><br>
    <button @click="btnHandler3">-1 Async</button><br>
    <button @click="btnHandler4">-N Async</button>
  </div>
</template>
<script>
import { mapState,mapMutations,mapActions } from 'vuex'
export default {
  name: "Subtraction",
  data(){
    return{
    }
  },
  computed:{
    ...mapState(['count'])
  },
  methods:{
    ...mapMutations(['sub','subN']),
    btnHandler1(){
      this.sub()
    },
    btnHandlerN(){
      this.subN(3)
    },
    ...mapActions(['subAsync','subAsyncN']),
    btnHandler3(){
      this.subAsync()
    },
    btnHandler4(){
      this.subAsyncN(6)
    }
  }
}
</script>
<style scoped>
</style>
(4)Getter
Getter用于对Store中的数据进行加工处理形成新的数据。
(1)Getter可以对Store中已有的数据加工处理之后形成新的数据,类似Vue的计算属性
(2)Store中数据发生变化,getter的数据也会跟着发生变化。

//定义Getter
export default new Vuex.Store({
  //state中存放的就是全局共享的数据
  state: {
    count: 0
  },
  //只有mutations中定义的函数,才有权力修改state中的数据
  mutations: {
    add(state){
      state.count++
    },
    addN(state,step){
      state.count += step
    },
    sub(state){
      state.count--
    },
    subN(state,step){
      state.count -= step
    },
  },
  actions: {
    addAsync(context){
      setTimeout(() =>{
        //在action中不能直接修改state中的数据
        //必须通过context.commit('add')来触发某个mutation才行
        context.commit('add')
      },1000)
    },
    addAsyncN(context,step){
      setTimeout(() =>{
        //在action中不能直接修改state中的数据
        //必须通过context.commit('add')来触发某个mutation才行
        context.commit('addN',step)
      },1000)
    },
    subAsync(context){
      setTimeout(() =>{
        //在action中不能直接修改state中的数据
        //必须通过context.commit('add')来触发某个mutation才行
        context.commit('sub')
      },1000)
    },
    subAsyncN(context,step){
      setTimeout(() =>{
        //在action中不能直接修改state中的数据
        //必须通过context.commit('add')来触发某个mutation才行
        context.commit('subN',step)
      },1000)
    }
  },
  getters: {
    showNum: state => {
      return '当前最新的数量时【'+ state.count+'】'
    }
  }
})

//getter的第一种使用方法
this.$store.getters.名称

//第二种使用方法
import { mapGetters } from 'vuex'
computed:{
  ...mapGetters(['showNum'])
}

当前的components/Addition.vue

<template>
  <div>
<!--    <h3>当前最新的count值为:{{$store.state.count}}</h3>-->
    <h3>当前最新的count值为:{{$store.getters.showNum}}</h3>
    <button @click="btnHandler1">+1</button><br>
    <button @click="btnHandlerN">+N</button><br>
    <button @click="btnHandler3">+1 Async</button><br>
    <button @click="btnHandler4">+N Async</button>
  </div>
</template>
<script>
export default {
name: "Addition",
  data(){
    return{
    }
  },
  methods:{
    btnHandler1(){
      this.$store.commit('add')
    },
    btnHandlerN(){
      //commit的作用,就是调用某个mutation函数
      this.$store.commit('addN',3)
    },
    //异步的让count自增1
    btnHandler3(){
      //这里的dispatch函数,专门用来触发action
      this.$store.dispatch('addAsync')
    },
    //异步的让count自增N
    btnHandler4(){
      //这里的dispatch函数,专门用来触发actions时携带参数
      this.$store.dispatch('addAsyncN',5)
    }
  }
}
</script>
<style scoped>
</style>

当前的components/Subtraction.vue

<template>
  <div>
<!--    <h3>当前最新的count值为:{{count}}</h3>-->
    <h3>当前最新的count值为:{{showNum}}</h3>
    <button @click="btnHandler1">-1</button><br>
    <button @click="btnHandlerN">-N</button><br>
    <button @click="btnHandler3">-1 Async</button><br>
    <button @click="btnHandler4">-N Async</button>
  </div>
</template>
<script>
import { mapState,mapMutations,mapActions,mapGetters } from 'vuex'
export default {
  name: "Subtraction",
  data(){
    return{
    }
  },
  computed:{
    ...mapState(['count']),
    ...mapGetters(['showNum'])
  },
  methods:{
    ...mapMutations(['sub','subN']),
    btnHandler1(){
      this.sub()
    },
    btnHandlerN(){
      this.subN(3)
    },
    ...mapActions(['subAsync','subAsyncN']),
    btnHandler3(){
      this.subAsync()
    },
    btnHandler4(){
      this.subAsyncN(6)
    },
  }
}
</script>
<style scoped>
</style>

项目地址:gitee源码地址

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你是董我的人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值