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