基础知识系列(四):Vue2的mixin和Vue3的hook

1.Vue2的mixin

在useCityMixin.js中

export default {
    data() {
      return {
        city: "武汉",
      };
    },
    methods: {
      changeCity() {
        this.city = "苏州";
      },
    },
    computed: {
      $city() {
        return "$" + this.city;
      },
    },
  };

在useCountMixin.js中

export default {
    data() {
      return {
        count: 1,
      };
    },
    methods: {
      addCount() {
        this.count++;
      },
    },
    computed: {
      double() {
        return this.count * 2;
      },
    },
  };

在App.vue中

<template>
  <div>
    <button @click="addCount">{{ count }}</button>
    <h2>{{ double }}</h2>
    <button @click="changeCity">{{ city }}</button>
    <h3>{{ $city }}</h3>
  </div>
</template>

<script>
import useCityMixin from './Mixins/useCityMixin'
import useCountMixin from './Mixins/useCounMixin'
export default {
  mixins:[useCityMixin,useCountMixin]
};
</script>

<style scoped></style>

2.Vue3的hook

在useCityHook.js中

import {ref,computed} from 'vue'
export const useCityHook = () => {
  // city
  const city = ref("武汉");
  const changeCity = () => {
    city.value = "苏州";
  };
  const $city = computed(() => {
    return "$" + city.value;
  });
  return {city,changeCity,$city}
};

在useCountHook.js中

import {ref,computed} from 'vue'
export const useCountHook = () => {
  // count
  const count = ref(0);
  const addCount = () => {
    count.value++;
  };
  const double = computed(() => {
    return count.value * 2;
  });
  return {count,addCount,double}
};

在App.vue中

<template>
  <div>
    <button @click="addCount">{{ count }}</button>
    <h4>{{ double }}</h4>
    <button @click="changeCity">{{ city }}</button>
    <h4>{{ $city }}</h4>
  </div>
</template>

<script setup>
import { useCityHook } from "./Hooks/useCityHook";
import { useCountHook } from "./Hooks/useCountHook";
const { city, changeCity, $city } = useCityHook();
const { count, addCount, double } = useCountHook();
</script>

<style coped></style>

 PS:文件夹组织:(公有):src→routes/components/Hooks→(私有):views→routes/components/Hooks

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值