vue中computed的详细讲解

1.定义

       computed是vue的计算属性,是根据依赖关系进行缓存的计算,只有在它的相关依赖发生改变时才会进行更新

2.用法

       一般情况下,computed默认使用的是getter属性
在这里插入图片描述

3.computed的响应式依赖(缓存)

       1. computed的每一个计算属性都会被缓存起来,只要计算属性所依赖的属性发生变化,计算属性就会重新执行,视图也会更新。下面代码中,计算属性fullName,它依赖了firstNamelastName这两个属性,只要它们其中一个属性变化,fullName就会重新执行。
       2.computed计算属性会被缓存,在下面代码中使用了两次fullName,但在控制台只输出了一次 “这是fullName”。

<template>
  <div>
    <div>
      姓:<input type="text" v-model="firstName" />
    </div>
    <div>
      名:<input type="text" v-model="lastName" />
    </div>
    <!-- 调用两次fullName -->
    <div>姓名:{{ fullName }}</div>
    <div>姓名:{{ fullName }}</div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      firstName: "张",
      lastName: "三",
    };
  },
  computed: {
    fullName() {
        console.log("这是fullName");
        return this.firstName + this.lastName;
    }
  }
};
</script>

4.应用场景

       当一个数据受多个数据影响时,可以使用computed
       1.本组件计算
       2.计算props的值
       3.计算vuex的state或者getters值的变化

参考:https://cn.vuejs.org/v2/guide/computed.html
           https://segmentfault.com/a/1190000012948175

  • 85
    点赞
  • 260
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
Vue使用Vuex进行状态管理是非常常见的,它可以帮助我们更好地组织和管理应用程序的状态。下面是一个简单的例子,演示如何在Vue使用Vuex进行传值。 1. 安装Vuex 首先,我们需要安装Vuex。可以使用npm或yarn来安装: ``` npm install vuex --save ``` 或者 ``` yarn add vuex ``` 2. 创建store 在Vue使用Vuex需要先创建一个store。在store,我们可以定义和管理应用程序的所有状态。 ``` import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++ } } }); export default store; ``` 在这个例子,我们定义了一个名为“count”的状态和一个名为“increment”的mutation,当我们调用“increment”mutation时,它会增加“count”状态的值。 3. 在Vue组件使用store 现在我们已经创建了一个store,接下来让我们在Vue组件使用它。我们需要使用Vuex提供的“mapState”和“mapMutations”辅助函数来访问store的状态和mutations。 ``` <template> <div> <h1>{{ count }}</h1> <button @click="increment">Increment</button> </div> </template> <script> import { mapState, mapMutations } from 'vuex'; export default { computed: { ...mapState(['count']) }, methods: { ...mapMutations(['increment']) } } </script> ``` 在这个例子,我们使用了“mapState”辅助函数来将“count”状态映射到组件的计算属性,并使用“mapMutations”辅助函数将“increment”mutation映射到组件的方法。这样,在组件就可以直接使用“count”状态和“increment”mutation了。 以上就是使用Vuex进行状态管理的基本过程。在实际开发,我们通常需要定义更多的状态和mutations,并使用actions和getters等高级特性来管理更复杂的状态。但基本的使用方法和原理都是相似的。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值