ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

vue3 reactive 实现响应式

2020-12-01 09:57:52  阅读:497  来源: 互联网

标签:const 响应 reactive add vue3 import font data


<template>
<div>

  <img alt="Vue logo" src="./assets/logo.png">
  <button @click = "add">add</button>

  <p>
    {{data.x}}--{{data.y}}

  </p>

</div>
  
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import HelloWorld from './components/HelloWorld.vue';

import {ref,reactive} from "vue";

export default defineComponent({
  name: 'App',
  setup(){
       //表明它是响应式的
    const count = ref(100);
    const data = reactive({
      x:100,
      y:100
    })
    const add = ()=>{
        // 写一段逻辑
       data.x += 88;
       data.y += 99;

    }
    // 必须返回模块中才能够使
  return {
    data,
    add
  }
  }
});
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

reactive 实现响应式和ref没有多大的差别,无非reactive(obj) 这个函数接收的是一个对象

而且修改的时候,可以直接修改值,不需要像ref 一样,修改带一个xxx.value 去修改

就这个点差别

上面的话,是将数组放到了data 中,假如我们想吧 x,y 暴露出去,这个时候就用到了toRefs ?

试试

<template>
<div>

  <img alt="Vue logo" src="./assets/logo.png">
  <button @click = "add">add</button>

  <p>
  {{x}}---{{y}}

  </p>

</div>
  
</template>

<script lang="ts">
import { defineComponent } from 'vue';
// import HelloWorld from './components/HelloWorld.vue';

import {reactive ,toRefs} from "vue";

export default defineComponent({
  name: 'App',
  setup(){

    const data = reactive({
      x:100,
      y:100
    })

  // reactData 展开好后自带响应式
    const reactData = toRefs(data);
    const add = ()=>{
        // 写一段逻辑
      data.x +=10;
      data.y +=10;

    }
    // 必须返回模块中才能够使
  return {
    add,
    ...reactData
  }
  }
});
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

修改的比较多,也可以实现类似的功能!

行,大家去测试下吧!同学加油!

 

 

 

标签:const,响应,reactive,add,vue3,import,font,data
来源: https://blog.csdn.net/qq_15009739/article/details/110421846

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有