美文网首页
vue组件传值&vuex

vue组件传值&vuex

作者: 404_accc | 来源:发表于2019-10-24 16:38 被阅读0次

vue技术分享

目录

一、vue组件之间的通信

1. 父组件传值给子组件 </br>
<!--父组件代码-->
<template>
  <div>
    <div  class="box">
      <h1>父组件</h1>
      <input type="text" v-model="msg"> <br>
      <div>
        <p>测试参数:{{msg}}</p>
      </div>
    </div>
    <div class="box">
      <Demo1Child :info="msg"></Demo1Child>
    </div>   
  </div>
</template>

<script>
import Demo1Child from '@/components/DemoChild'
export default {
  name: 'HelloWorld',
  components:{
    Demo1Child
  },
  data () {
    return {
      msg: ''
    }
  }
}
</script>
<!--子组件代码-->
<template>
  <div>
    <h1>子组件</h1>
    <input type="text" v-model="info"> <br>
    <p>{{info}}</p>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {  
    info: {  
      type: String,  
      default: function () {  
        return ''  
      }  
    }  
  }
}
</script>

父组件使用属性绑定的方式给子组件绑定需要给子组件传递的数据,子组件使用props接收。(子组件直接使用 input, v-model绑定props此处有坑) ==demochild1==

2. 子组件给父组件传递参数
<!--父组件代码-->
<template>
  <div>
    <div  class="box">
      <h1>父组件</h1>
      <div>
        <p>子组件传递上来的参数:{{childrenData}}</p>
      </div>
    </div>
    <div class="box">
      <DemoChild2 :info="msg" v-on:listenChildEvent="showChildData"></DemoChild2>
    </div>
  </div>
</template>

<script>
import DemoChild2 from '@/components/DemoChild2';
export default {
  name: 'HelloWorld',
  components:{
    DemoChild1,
    DemoChild2
  },
  data () {
    return {
      msg: '',
      childrenData:''
    }
  },
  methods:{
    showChildData(data){
      this.childrenData = data;
    }
  }
}
</script>
<!--子组件代码-->
<template>
  <div>
    <h1>子组件</h1>
    <input type="text" v-model="childData" @change="emitFather()"> <br>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data(){
    return{
      childData:''
    }
  },
  methods:{
    emitFather(){
      this.$emit('listenChildEvent',this.childData);
    }
  }
}
</script>

子组件中需要以某种方式例如点击事件的方法来触发一个自定义事件; </br>
将需要传的值作为$emit的第二个参数,该值将作为实参传给响应自定义事件的方法;</br>
在父组件中注册子组件并在子组件标签上使用 v-on 对自定义事件的监听 ==DemoChild2==

3. 父子组件数据的双向通信

==prop 是单向绑定的==:当父组件的属性变化时,将传导给子组件,但是不会反过来。这是为了防止子组件无意修改了父组件的状态——这会让应用的数据流难以理解。
另外,每次父组件更新时,子组件的所有 prop 都会更新为最新值。这意味着你不应该在子组件内部改变 prop。如果你这么做了,Vue 会在控制台给出警告 ==DemoChild3==

<!--父组件代码-->
<template>
  <div>
    <div  class="box">
      <h1>父组件3</h1>
      <div>
        <input type="text" v-model="msg">
        <p>{{msg}}</p>
      </div>
    </div>
    <div class="box">
      <DemoChild3 :msg.sync="msg"></DemoChild3>
    </div>
  </div>
</template>

<script>
import DemoChild3 from '@/components/DemoChild3';
export default {
  name: 'HelloWorld',
  components:{
    DemoChild1,
    DemoChild2,
    DemoChild3
  },
  data () {
    return {
      msg: '',
      childrenData:''
    }
  },
  methods:{
    showChildData(data){
      this.childrenData = data;
    }
  }
}
<!--子组件代码-->
<template>
  <div>
    <h1>子组件3</h1>
    <input type="text" v-model="childData"> <br>
    <p>{{msg}}</p>
    <input type="button" value="点我加一下" @click="emitFather()">
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data(){
    return{
      childData:''
    }
  },
  props: {  
    msg: {  
      type: String,  
      default: function () {  
        return ''  
      }  
    }  
  },
  methods:{
    emitFather(){
      this.$emit('update:msg',this.childData);
    }
  }
}
</script>
4. 非父子组件之间的通信

实现非父子组件间的通信,可以通过创建一个vue实例Bus作为媒介,要相互通信的兄弟组件之中,都引入Bus,之后通过分别调用Bus事件触发和监听来实现组件之间的通信和参数传递。

<!--bus.js-->
import Vue from 'vue';
export default new Vue;
<!--组件一-->
<template>
  <div>
    <h1>组件一</h1>
    <input type="text" v-model="message"> 
    <input type="button" value="确认传递参数" @click="bus()">
  </div>
</template>
<script>
import Bus from './bus'
export default {
  data () {
    return {
      message:'111',
    };
  },
  methods:{
    bus () {
      Bus.$emit('msg',this.message);
    }
  }
}
<!--组件二-->
<template>
  <div>
    <h1>组件二</h1>
    <p>{{message}}</p>
  </div>
</template>
<script>
import Bus from './bus'
export default {
  data () {
    return {
      message:''
    };
  },
  mounted() {
  let self = this;
    Bus.$on('msg', (e) => {
      self.message = e
     console.log(`传来的数据是:${e}`);
    })
  }  
}

二、vuex状态管理

  • 多个视图依赖于同一状态。
  • 来自不同视图的行为需要变更同一状态。

对于问题一,传参的方法对于多层嵌套的组件将会非常繁琐,并且对于兄弟组件间的状态传递无能为力。
对于问题二,我们经常会采用父子组件直接引用或者通过事件来变更和同步状态的多份拷贝。以上的这些模式非常脆弱,通常会导致无法维护的代码。


vuex是一个专门为vue.js设计的集中式状态管理架构。状态?我把它理解为在data中的属性需要共享给其他vue组件使用的部分,就叫做状态。简单的说就是data中需要共用的属性。比如:我们有几个页面要显示用户名称和用户等级,或者显示用户的地理位置。如果我们不把这些属性设置为状态,那每个页面遇到后,都会到服务器进行查找计算,返回后再显示。

  • 首先安装vuex插件 npm install vuex --save
  1. State
  2. Mutation
  3. Getter
  4. Action
  5. Module

State:这个就是我们说的访问状态对象,它就单页应用中的共享值。怎么将状态对象赋值给内部对象,也就是把stroe.js中的值,赋值给模板里data中的值。一般有三种方式。

1.通过computed的计算属性直接赋值

computed属性可以在输出前,对data中的值进行改变,我们就利用这种特性把store.js中的state值赋值给我们模板中的data值。

computed:{
    test(){
        return this.$store.state.count;   //store.state.count
    }
},
store
2.mapState 辅助函数——通过对象赋值

需要在组件中引入==import {mapState} from 'vuex';==

computed:mapState({
    test:function(state){
      return state.count;
    }
}),
3.mapState 辅助函数——通过数组赋值
computed:mapState(["count"])

Mutation:更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。要想更改store中state的值,只能通过mutation。

1.Vuex提供了==commit==方法来修改状态

组件中这样使用commit

<button @click="$store.commit('add')">+</button>
<button @click="$store.commit('reduce')">-</button>

store.js中这样定义mutation

const mutations={
  add(state){
      state.count++;
  },
  reduce(state){
      state.count--;
  }
}
2.提交载荷(Payload)——传值

组件中这样定义传值

<button @click="$store.commit('add','this')">+</button>

store.js中这样定义mutation中的add方法

const mutations={
  add(state,test){
    state.count = test;
  },
  reduce(state){
      state.count--;
  }
}
3.模板获取mutation中的方法

需要在组件中引入 ==import {mapMutations} from 'vuex';==

组件中js代码可以这样写

methods:{
    ...mapMutations(['add','reduce']),
},

组件中的html代码可以这样写

<button @click="add('this')">+</button>

Getters:getters从表面是获得的意思,可以把他看作在获取数据之前进行的一种再编辑,相当于对数据的一个过滤和加工

在store.js中这样写

const getters = {
    count:function(state){
        return state.count +=100;
    }
}

在组件中这样写

computed:{
    // count(){
    //     return this.$store.getters.count;
    // },
    ...mapGetters(["count"])
  }

Actions:actions和的Mutations功能基本一样,不同点是,actions是异步的改变state状态,而Mutations是同步改变状态

在store.js中这样写

const actions ={
    addAction(doAnything){
        // doAnything.commit('add',5)
        setTimeout(function(){
            doAnything.commit('add',5);
        },3000)
        console.log('我比add提前执行');
    },
    reduceAction({commit}){
        commit('reduce')
    }
}

在组件中这样写

methods:{
    ...mapMutations([  
      'add','reduce'
    ]),
    ...mapActions(['addAction','reduceAction'])
}

三、vue中数据监听watch的使用

watch首先是一个对象,是对象就有键名(你要监听的对象数据),键值(可以是函数,函数名,对象),键值如果是对象选项有三个

  • 第一个handler:其值是一个回调函数。即监听到变化时应该执行的函数(不能使用箭头函数)。
  • 第二个是deep:其值是true或false;确认是否深入监听。(一般监听时是不能监听到对象属性值的变化的,数组的值变化可以听到。)
  • 第三个是immediate:其值是true或false;确认是否以当前的初始值执行handler的函数。
<template>
  <div>
        <p>今天挣了{{money}}元</p>
        <p>晚餐可以吃个{{food}}</p>
        <p>
            <button @click="add">加班</button>
            <button @click="reduce">偷懒</button>
        </p>
        <input type="text" v-model="arr[0]"> <br>
        <input type="text" v-model="obj.name">
  </div>
</template>

<script>
var foods=['菜夹馍','肉夹馍','牛肉面','肯德基全家桶','六菜一汤'];
export default {
  data () {
    return {
        food:'菜夹馍',
        money:5,
        arr:[1,2,3,4],
        obj:{
            name:'李四',
            age:18,
            sex:'女'
        }
    };
  },
  methods:{
    add:function(){
        this.money+=5;
    },
    reduce:function(){
        this.money-=5;
    }
  },
  watch:{
    money:function(newVal,oldVal){
        if(newVal<5){
            this.food = '土'
        }else if(newVal==5){
            this.food=foods[0];
        }else if(newVal==10)
        {
            this.food=foods[1];
        }else if(newVal==15)
        {
            this.food=foods[2];
        }else if(newVal==20)
        {
            this.food=foods[3];
        }else{
            this.food=foods[4];
        }
    },
    arr:{
        handler(curVal,oldVal){

       console.log(curVal,oldVal)
     },
//      deep:true
    },
    obj:{
        handler(newVal,oldVal){
            console.log(newVal,oldVal);
        },
        deep:true
    }
  }
}

</script>

注意项:在使用数据监听的同时要使用原声js获取DOM节点,一定要加上非空判断,不然代码容易报错

watch: {
    'name': function (newVal, oldVal) {
      this.variable_arr = []
      this.temp = []
      if (newVal.content && newVal.content !== '') {
        let str = newVal.content.replace('%storeName%', `(${this.currentStore.store_name})`)
        let temp = []
        this.temp = str.split('%')
        this.temp.forEach((v, index) => {
          if ((index + 1) % 2 !== 0) {
            temp.push(v)
          }
        })
        this.views = temp.join('')
        this.count = Math.ceil((this.views.length + this.identification.length) / 70) * this.phone_list.length
      }
      if (document.getElementsByClassName('smsref') && document.getElementsByClassName('smsref')[0]) {
        document.getElementById('refForm').reset()
      }
    },
},

四、vue里ref ($refs)用法

ref 有三种用法 https://www.cnblogs.com/goloving/p/9404099.html

  1. ref 加在普通的元素上,用this.ref.name 获取到的是dom元素
  2. ref 加在子组件上,用this.ref.name 获取到的是组件实例,==可以使用组件的所有方法。==
  3. 如何利用 v-for 和 ref 获取一组数组或者dom 节点

相关文章

  • Vue组件之间的传值

    Vue父子组件之间的传值(props)兄弟组件 VUEX

  • 2020-03月前端面试题

    vue相关 vue父子组件传值方式有哪些? 兄弟组件间如何传值? vuex是用来干什么的? vuex核心模块有哪些...

  • vuex

    关于vuex vuex 是适用于vue框架的状态管理工具,适用于组件与组件之间传值。 vue安装 npm安装命令:...

  • vue组件间传值之eventBus

    1 概述: vue组件间的传值,父子之间props 和emit; 跨组件间可以使用vuex或者eventBus; ...

  • vue兄弟组件传值三种方法总结

    在vue开发中总会遇到组件传值问题,今天总结一下兄弟组件之间的传值方法。1、子传父,父传子2、vuex3、even...

  • vue兄弟组件传值三种方法总结

    在vue开发中总会遇到组件传值问题,今天总结一下兄弟组件之间的传值方法。1. 子传父,父传子 2. vuex 3....

  • 第5讲 vuex看完这篇你就会了(1)

    vuex和vue-router一样都是vue的核心插件,它是vue的状态管理,对于跨组件之间的传值,可以将这些值放...

  • 2018-09-28

    1.vue 路由跳转传值 -------- 最好用vuex,bus不适合在路由跳转中传值,因为需要初始化组件 2....

  • VUE08--{VUEX}

    VUEX是什么 管理(修改或设置)组件用到的数据的工具。免除了之前组件传值的麻烦。组件传值 VUEX组成 stor...

  • vue组件传值&vuex

    vue技术分享 目录 vue组件之间的通信 vue中数据监听watch的使用 vuex状态管理 vue-aweso...

网友评论

      本文标题:vue组件传值&vuex

      本文链接:https://www.haomeiwen.com/subject/osddvctx.html